diff --git a/.github/workflows/ci-full.yml b/.github/workflows/ci-full.yml index 69c1898bc8f..c8f4191b7e4 100644 --- a/.github/workflows/ci-full.yml +++ b/.github/workflows/ci-full.yml @@ -132,8 +132,8 @@ jobs: # and leave a stale digest that only fails after the download. Both values # are the ubuntu-22.04-x86_64 row of `crates/openhuman-core/src/modules/registry.rs`, # which is the authoritative pin — copy them from there, never recompute. - memory_version="1.17.0" - memory_sha256="0b0305bddbee09b3fe9965395fe9d006526f0c0c2ffd777d6e78747b2cfcff35" + memory_version="1.20.0" + memory_sha256="d3c2485a3fdd657b40ba65ab266950bd3f3f060695a9bba3e20b2d83e343fb61" module_root="/opt/openhuman-test-modules/${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" memory_dir="$module_root/tinymemory" juice_dir="$module_root/tinyjuice" @@ -333,8 +333,8 @@ jobs: # tinybus validates every directory ancestor. GitHub mounts the # checkout as the host runner uid while this container runs as root, # so keep native fixtures in a root-owned, ephemeral tree. - memory_version="1.17.0" - memory_sha256="0b0305bddbee09b3fe9965395fe9d006526f0c0c2ffd777d6e78747b2cfcff35" + memory_version="1.20.0" + memory_sha256="d3c2485a3fdd657b40ba65ab266950bd3f3f060695a9bba3e20b2d83e343fb61" module_root="/opt/openhuman-test-modules/${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" memory_dir="$module_root/tinymemory" juice_dir="$module_root/tinyjuice" diff --git a/.github/workflows/ci-lite.yml b/.github/workflows/ci-lite.yml index 07711638eb2..098c759c179 100644 --- a/.github/workflows/ci-lite.yml +++ b/.github/workflows/ci-lite.yml @@ -678,8 +678,8 @@ jobs: # and leave a stale digest that only fails after the download. Both values # are the ubuntu-22.04-x86_64 row of `crates/openhuman-core/src/modules/registry.rs`, # which is the authoritative pin — copy them from there, never recompute. - memory_version="1.17.0" - memory_sha256="0b0305bddbee09b3fe9965395fe9d006526f0c0c2ffd777d6e78747b2cfcff35" + memory_version="1.20.0" + memory_sha256="d3c2485a3fdd657b40ba65ab266950bd3f3f060695a9bba3e20b2d83e343fb61" module_root="/opt/openhuman-test-modules/${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" memory_dir="$module_root/tinymemory" juice_dir="$module_root/tinyjuice" diff --git a/.github/workflows/e2e-playwright.yml b/.github/workflows/e2e-playwright.yml index 5ce7fb34e70..be915e42cec 100644 --- a/.github/workflows/e2e-playwright.yml +++ b/.github/workflows/e2e-playwright.yml @@ -68,8 +68,8 @@ jobs: # tinybus validates every directory ancestor. GitHub mounts the # checkout as the host runner uid while this container runs as root, # so keep native fixtures in a root-owned, ephemeral tree. - memory_version="1.17.0" - memory_sha256="0b0305bddbee09b3fe9965395fe9d006526f0c0c2ffd777d6e78747b2cfcff35" + memory_version="1.20.0" + memory_sha256="d3c2485a3fdd657b40ba65ab266950bd3f3f060695a9bba3e20b2d83e343fb61" module_root="/opt/openhuman-test-modules/${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" memory_dir="$module_root/tinymemory" juice_dir="$module_root/tinyjuice" diff --git a/.github/workflows/e2e-reusable.yml b/.github/workflows/e2e-reusable.yml index cd322b89111..3361c6a4a46 100644 --- a/.github/workflows/e2e-reusable.yml +++ b/.github/workflows/e2e-reusable.yml @@ -168,8 +168,8 @@ jobs: # and leave a stale digest that only fails after the download. Both values # are the ubuntu-22.04-x86_64 row of `crates/openhuman-core/src/modules/registry.rs`, # which is the authoritative pin — copy them from there, never recompute. - memory_version="1.17.0" - memory_sha256="0b0305bddbee09b3fe9965395fe9d006526f0c0c2ffd777d6e78747b2cfcff35" + memory_version="1.20.0" + memory_sha256="d3c2485a3fdd657b40ba65ab266950bd3f3f060695a9bba3e20b2d83e343fb61" module_root="/opt/openhuman-test-modules/${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" memory_dir="$module_root/tinymemory" memory_archive="$memory_dir/tinymemory-module-${memory_version}-ubuntu-22.04-x86_64.tar.gz" @@ -373,8 +373,8 @@ jobs: # and leave a stale digest that only fails after the download. Both values # are the ubuntu-22.04-x86_64 row of `crates/openhuman-core/src/modules/registry.rs`, # which is the authoritative pin — copy them from there, never recompute. - memory_version="1.17.0" - memory_sha256="0b0305bddbee09b3fe9965395fe9d006526f0c0c2ffd777d6e78747b2cfcff35" + memory_version="1.20.0" + memory_sha256="d3c2485a3fdd657b40ba65ab266950bd3f3f060695a9bba3e20b2d83e343fb61" module_root="/opt/openhuman-test-modules/${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" memory_dir="$module_root/tinymemory" connectors_dir="$module_root/tinyconnectors" @@ -487,8 +487,8 @@ jobs: # fixture outside the checkout owned by the host runner. # Version and digest are the ubuntu-22.04-x86_64 registry pin; do # not derive a replacement checksum from a local build. - memory_version="1.17.0" - memory_sha256="0b0305bddbee09b3fe9965395fe9d006526f0c0c2ffd777d6e78747b2cfcff35" + memory_version="1.20.0" + memory_sha256="d3c2485a3fdd657b40ba65ab266950bd3f3f060695a9bba3e20b2d83e343fb61" juice_version="0.4.0" juice_sha256="c404fa25c54c6e3888fdbdd971be9055f1e46e947c854f1556069a4e0d0390da" module_root="/opt/openhuman-test-modules/${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" diff --git a/Cargo.lock b/Cargo.lock index a18a9dfe497..b566c549507 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7045,7 +7045,7 @@ dependencies = [ [[package]] name = "tinymemory" -version = "1.19.0" +version = "1.20.0" dependencies = [ "anyhow", "async-trait", diff --git a/app/src/components/chat/ChatFilesPanel.tsx b/app/src/components/chat/ChatFilesPanel.tsx index 4ee9ae1ac08..57bfcbec86c 100644 --- a/app/src/components/chat/ChatFilesPanel.tsx +++ b/app/src/components/chat/ChatFilesPanel.tsx @@ -6,7 +6,7 @@ import { type ArtifactErrorCode, deleteArtifact, downloadArtifact, - revealArtifactInFileManager, + revealArtifact, } from '../../services/artifactDownloadService'; import { type ArtifactSnapshot, @@ -23,7 +23,8 @@ import { extensionFor } from './artifactExtension'; * Mounted by {@link ChatFilesChip}. Renders one row per artifact with: * - kind icon + title + human-readable size * - Download (Tauri `download_artifact_to_downloads`) - * - Show-in-folder (only after a successful download in this session) + * - Show in folder: opens the file manager at the artifact's real file in + * the visible files folder (#5505) * - Delete with a confirm-step (optimistic slice removal + RPC call, * re-upsert on failure with a toast). * @@ -64,6 +65,8 @@ function localizeErrorCode( return t('chat.files.error.download_failed'); case 'DELETE_FAILED': return t('chat.files.error.delete_failed'); + case 'REVEAL_FAILED': + return t('chat.files.error.reveal_failed'); case 'CANCELLED': // User-initiated dialog dismissal — not a real error. Callers treat // it as a no-op; surface nothing (fall back to raw text if passed). @@ -155,7 +158,6 @@ function KindIcon({ kind }: { kind: ArtifactSnapshot['kind'] }) { interface RowDownloadState { state: 'idle' | 'downloading' | 'done' | 'error'; - path?: string; /** Already-localized error headline ready for direct render. */ error?: string; } @@ -167,6 +169,8 @@ export default function ChatFilesPanel({ threadId, artifacts, onClose }: ChatFil const [confirmDeleteId, setConfirmDeleteId] = useState(null); const [downloadState, setDownloadState] = useState>({}); const [deleteError, setDeleteError] = useState(null); + // Per-row "Show in folder" failure, already localized. + const [revealError, setRevealError] = useState>({}); // Esc closes. Use keydown not keyup so a panel that opened via Enter // doesn't immediately re-trigger its trigger on the same release. @@ -206,7 +210,7 @@ export default function ChatFilesPanel({ threadId, artifacts, onClose }: ChatFil setDownloadState(prev => ({ ...prev, [artifact.artifactId]: outcome.ok - ? { state: 'done', path: outcome.path } + ? { state: 'done' } : { state: 'error', // Prefer the localized headline; only fall back to the raw @@ -217,9 +221,14 @@ export default function ChatFilesPanel({ threadId, artifacts, onClose }: ChatFil })); }; - const handleReveal = async (path: string) => { - if (path) { - await revealArtifactInFileManager(path); + const handleReveal = async (artifact: ArtifactSnapshot) => { + setRevealError(({ [artifact.artifactId]: _cleared, ...rest }) => rest); + const outcome = await revealArtifact(artifact.artifactId); + if (!outcome.ok) { + setRevealError(prev => ({ + ...prev, + [artifact.artifactId]: localizeErrorCode(t, outcome.code, outcome.error), + })); } }; @@ -341,17 +350,15 @@ export default function ChatFilesPanel({ threadId, artifacts, onClose }: ChatFil ? t('chat.artifact.downloading') : t('chat.artifact.download')} - {row.state === 'done' && row.path && ( - - )} + - + {localStore ? ( + <> + {/* Destructive actions — muted, set apart behind a divider. */} + + - + + + ) : null} {/* Secondary actions — quiet ghost buttons. */} - {contentRootAbs ? ( + {localStore && contentRootAbs ? ( ) : null} {/* Primary action. */} - + {localStore ? ( + + ) : null} ); diff --git a/app/src/components/settings/panels/AgentAccessPanel.tsx b/app/src/components/settings/panels/AgentAccessPanel.tsx index c46d0126350..b158d67de68 100644 --- a/app/src/components/settings/panels/AgentAccessPanel.tsx +++ b/app/src/components/settings/panels/AgentAccessPanel.tsx @@ -25,6 +25,7 @@ import { import { useSettingsNavigation } from '../hooks/useSettingsNavigation'; import SettingsPanel from '../layout/SettingsPanel'; import AutonomyRateLimitSection from './AutonomyPanel'; +import FilesFolderSection from './FilesFolderSection'; // Installs are always *available* but never silent: every `install_tool` call // is routed through the approval gate, so the user is asked to Approve/Deny @@ -336,6 +337,8 @@ const AgentAccessPanel = () => { {/* ── File system: where the agent may read and write ─────────── */} + + { + const { t } = useT(); + const [paths, setPaths] = useState(null); + const [input, setInput] = useState(''); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(null); + const [savedNote, setSavedNote] = useState(null); + // Last write wins: a slow response must not overwrite a newer one. + const seqRef = useRef(0); + + useEffect(() => { + let cancelled = false; + void (async () => { + try { + const resp = await openhumanGetAgentPaths(); + if (cancelled) return; + setPaths(resp.result); + setInput(resp.result.files_dir); + } catch { + if (!cancelled) setError(t('settings.agentAccess.filesFolder.loadError')); + } + })(); + return () => { + cancelled = true; + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + const save = async (value: string) => { + const seq = ++seqRef.current; + setSaving(true); + setError(null); + setSavedNote(null); + try { + const resp = await openhumanUpdateAgentPaths({ files_dir: value }); + if (seq !== seqRef.current) return; + setPaths(resp.result); + setInput(resp.result.files_dir); + setSavedNote(t('settings.agentAccess.filesFolder.saved')); + } catch (e) { + if (seq !== seqRef.current) return; + setError(e instanceof Error ? e.message : String(e)); + } finally { + if (seq === seqRef.current) setSaving(false); + } + }; + + const openFolder = async () => { + if (!paths) return; + setError(null); + try { + await revealPath(paths.files_dir); + } catch { + setError(t('settings.agentAccess.filesFolder.openError')); + } + }; + + const trimmed = input.trim(); + const unchanged = paths !== null && trimmed === paths.files_dir; + + return ( +
+
+
+ {t('settings.agentAccess.filesFolder.label')} +
+

+ {t('settings.agentAccess.filesFolder.desc')} +

+
+
+ setInput(e.target.value)} + placeholder={paths?.default_files_dir} + aria-label={t('settings.agentAccess.filesFolder.label')} + disabled={paths === null} + onKeyDown={e => { + if (e.key === 'Enter' && trimmed && !unchanged) { + e.preventDefault(); + void save(trimmed); + } + }} + inputSize="sm" + data-testid="files-folder-input" + /> + + + {paths?.files_dir_source === 'override' && ( + + )} +
+ {(saving || savedNote || error) && ( +
+ +
+ )} +
+ ); +}; + +export default FilesFolderSection; diff --git a/app/src/components/settings/panels/MemoryDataPanel.tsx b/app/src/components/settings/panels/MemoryDataPanel.tsx index 386ad4b3927..7f2872fa633 100644 --- a/app/src/components/settings/panels/MemoryDataPanel.tsx +++ b/app/src/components/settings/panels/MemoryDataPanel.tsx @@ -88,7 +88,8 @@ const MemoryDataPanel = ({ embedded = false }: MemoryDataPanelProps = {}) => { - + {/* The vault is the local chunk store's files: hosted memory has none. */} + diff --git a/app/src/components/settings/panels/__tests__/AgentAccessPanel.defaults.test.tsx b/app/src/components/settings/panels/__tests__/AgentAccessPanel.defaults.test.tsx index 0184cc88f4d..0af0187b1fe 100644 --- a/app/src/components/settings/panels/__tests__/AgentAccessPanel.defaults.test.tsx +++ b/app/src/components/settings/panels/__tests__/AgentAccessPanel.defaults.test.tsx @@ -90,6 +90,20 @@ vi.mock('../../../../utils/tauriCommands', async () => { openhumanUpdateAutonomySettings: vi.fn(), openhumanGetAgentSettings: vi.fn(), openhumanUpdateAgentSettings: vi.fn(), + // The "Files folder" row (#5505) reads the agent paths on mount. + openhumanGetAgentPaths: vi.fn(async () => ({ + result: { + action_dir: '/home/u/OpenHuman/projects', + workspace_dir: '/home/u/.openhuman/users/u/workspace', + projects_dir: '/home/u/OpenHuman/projects', + action_dir_source: 'default', + files_dir: '/home/u/OpenHuman/projects/Files', + default_files_dir: '/home/u/OpenHuman/projects/Files', + files_dir_source: 'default', + }, + logs: [], + })), + openhumanUpdateAgentPaths: vi.fn(), }; }); diff --git a/app/src/components/settings/panels/__tests__/AgentAccessPanel.test.tsx b/app/src/components/settings/panels/__tests__/AgentAccessPanel.test.tsx index 4dcfb8c4388..3e03f04f75b 100644 --- a/app/src/components/settings/panels/__tests__/AgentAccessPanel.test.tsx +++ b/app/src/components/settings/panels/__tests__/AgentAccessPanel.test.tsx @@ -62,8 +62,20 @@ vi.mock('../../../../utils/tauriCommands', async () => { openhumanUpdateAutonomySettings: vi.fn(), openhumanGetAgentSettings: vi.fn(), openhumanUpdateAgentSettings: vi.fn(), - // The advanced panel no longer calls the agent-paths RPCs (action-dir - // moved to PermissionsPanel) — no mock needed, but keep the import clean. + // The "Files folder" row (#5505) reads the agent paths on mount. + openhumanGetAgentPaths: vi.fn(async () => ({ + result: { + action_dir: '/home/u/OpenHuman/projects', + workspace_dir: '/home/u/.openhuman/users/u/workspace', + projects_dir: '/home/u/OpenHuman/projects', + action_dir_source: 'default', + files_dir: '/home/u/OpenHuman/projects/Files', + default_files_dir: '/home/u/OpenHuman/projects/Files', + files_dir_source: 'default', + }, + logs: [], + })), + openhumanUpdateAgentPaths: vi.fn(), }; }); @@ -92,6 +104,7 @@ describe('AgentAccessPanel (advanced)', () => { expect(await screen.findByText('Confine to workspace')).toBeInTheDocument(); expect(screen.getByText('Granted folders')).toBeInTheDocument(); expect(screen.getByText('Always-allowed tools')).toBeInTheDocument(); + expect(screen.getByText('Files folder')).toBeInTheDocument(); }); it('toggling "confine to workspace" persists workspace_only', async () => { diff --git a/app/src/components/settings/panels/__tests__/FilesFolderSection.test.tsx b/app/src/components/settings/panels/__tests__/FilesFolderSection.test.tsx new file mode 100644 index 00000000000..5c0cda005ae --- /dev/null +++ b/app/src/components/settings/panels/__tests__/FilesFolderSection.test.tsx @@ -0,0 +1,143 @@ +import { fireEvent, screen, waitFor } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { renderWithProviders } from '../../../../test/test-utils'; +import { revealPath } from '../../../../utils/openUrl'; +import { + type AgentPaths, + openhumanGetAgentPaths, + openhumanUpdateAgentPaths, +} from '../../../../utils/tauriCommands'; +import FilesFolderSection from '../FilesFolderSection'; + +vi.mock('../../../../utils/tauriCommands', async () => { + const actual = await vi.importActual( + '../../../../utils/tauriCommands' + ); + return { ...actual, openhumanGetAgentPaths: vi.fn(), openhumanUpdateAgentPaths: vi.fn() }; +}); + +vi.mock('../../../../utils/openUrl', () => ({ revealPath: vi.fn() })); + +const DEFAULT = '/home/u/OpenHuman/projects/Files'; + +const paths = (overrides: Partial = {}): AgentPaths => ({ + action_dir: '/home/u/OpenHuman/projects', + workspace_dir: '/home/u/.openhuman/users/u/workspace', + projects_dir: '/home/u/OpenHuman/projects', + action_dir_source: 'default', + files_dir: DEFAULT, + default_files_dir: DEFAULT, + files_dir_source: 'default', + ...overrides, +}); + +const mockGet = vi.mocked(openhumanGetAgentPaths); +const mockUpdate = vi.mocked(openhumanUpdateAgentPaths); + +const input = () => screen.getByTestId('files-folder-input') as HTMLInputElement; + +describe('FilesFolderSection', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockGet.mockResolvedValue({ result: paths(), logs: [] }); + }); + + it('shows the folder the core reports', async () => { + renderWithProviders(); + await waitFor(() => expect(input().value).toBe(DEFAULT)); + expect(screen.getByText('Files folder')).toBeInTheDocument(); + // Nothing to save until the path changes, and no reset for the default. + expect(screen.getByTestId('files-folder-save')).toBeDisabled(); + expect(screen.queryByTestId('files-folder-reset')).not.toBeInTheDocument(); + }); + + it('saves a new folder and shows what the core stored', async () => { + mockUpdate.mockResolvedValue({ + result: paths({ files_dir: '/data/Deliverables', files_dir_source: 'override' }), + logs: [], + }); + renderWithProviders(); + await waitFor(() => expect(input().value).toBe(DEFAULT)); + + fireEvent.change(input(), { target: { value: ' /data/Deliverables ' } }); + fireEvent.click(screen.getByTestId('files-folder-save')); + + await waitFor(() => + expect(mockUpdate).toHaveBeenCalledWith({ files_dir: '/data/Deliverables' }) + ); + expect(await screen.findByText('Files folder updated')).toBeInTheDocument(); + expect(input().value).toBe('/data/Deliverables'); + expect(screen.getByTestId('files-folder-reset')).toBeInTheDocument(); + }); + + it('Enter saves too', async () => { + mockUpdate.mockResolvedValue({ result: paths({ files_dir: '/data/F' }), logs: [] }); + renderWithProviders(); + await waitFor(() => expect(input().value).toBe(DEFAULT)); + fireEvent.change(input(), { target: { value: '/data/F' } }); + fireEvent.keyDown(input(), { key: 'Enter' }); + await waitFor(() => expect(mockUpdate).toHaveBeenCalledWith({ files_dir: '/data/F' })); + }); + + it('"Use default" clears the override', async () => { + mockGet.mockResolvedValue({ + result: paths({ files_dir: '/data/Mine', files_dir_source: 'override' }), + logs: [], + }); + mockUpdate.mockResolvedValue({ result: paths(), logs: [] }); + renderWithProviders(); + + fireEvent.click(await screen.findByTestId('files-folder-reset')); + + await waitFor(() => expect(mockUpdate).toHaveBeenCalledWith({ files_dir: '' })); + await waitFor(() => expect(input().value).toBe(DEFAULT)); + expect(screen.queryByTestId('files-folder-reset')).not.toBeInTheDocument(); + }); + + it("shows the core's reason when a folder is refused", async () => { + mockUpdate.mockRejectedValue( + new Error('files_dir must not be inside the OpenHuman data folder: /home/u/.openhuman/x') + ); + renderWithProviders(); + await waitFor(() => expect(input().value).toBe(DEFAULT)); + fireEvent.change(input(), { target: { value: '/home/u/.openhuman/x' } }); + fireEvent.click(screen.getByTestId('files-folder-save')); + + expect( + await screen.findByText(/must not be inside the OpenHuman data folder/) + ).toBeInTheDocument(); + expect(input().value).toBe('/home/u/.openhuman/x'); + }); + + it('says so when the folder cannot be loaded', async () => { + mockGet.mockRejectedValue(new Error('core down')); + renderWithProviders(); + expect(await screen.findByText('Could not load the files folder.')).toBeInTheDocument(); + expect(input()).toBeDisabled(); + }); + + it('Show in folder opens the configured folder', async () => { + mockGet.mockResolvedValue({ + result: paths({ files_dir: '/data/Mine', files_dir_source: 'override' }), + logs: [], + }); + vi.mocked(revealPath).mockResolvedValueOnce(undefined); + renderWithProviders(); + await waitFor(() => expect(input().value).toBe('/data/Mine')); + + fireEvent.click(screen.getByTestId('files-folder-open')); + + await waitFor(() => expect(revealPath).toHaveBeenCalledWith('/data/Mine')); + }); + + it('says so when the folder cannot be opened', async () => { + vi.mocked(revealPath).mockRejectedValueOnce(new Error('no file manager')); + renderWithProviders(); + await waitFor(() => expect(input().value).toBe(DEFAULT)); + + fireEvent.click(screen.getByTestId('files-folder-open')); + + expect(await screen.findByText('Couldn’t open the files folder.')).toBeInTheDocument(); + }); +}); diff --git a/app/src/components/settings/panels/__tests__/PermissionsPanel.races.test.tsx b/app/src/components/settings/panels/__tests__/PermissionsPanel.races.test.tsx index 8a50ef35dfd..9c648223515 100644 --- a/app/src/components/settings/panels/__tests__/PermissionsPanel.races.test.tsx +++ b/app/src/components/settings/panels/__tests__/PermissionsPanel.races.test.tsx @@ -44,6 +44,9 @@ const agentPaths = (overrides: Partial = {}): AgentPaths => ({ workspace_dir: '/home/test/.openhuman/users/u1/workspace', projects_dir: '/home/test/OpenHuman/projects', action_dir_source: 'default', + files_dir: '/home/test/OpenHuman/projects/Files', + default_files_dir: '/home/test/OpenHuman/projects/Files', + files_dir_source: 'default', ...overrides, }); diff --git a/app/src/components/settings/panels/__tests__/PermissionsPanel.test.tsx b/app/src/components/settings/panels/__tests__/PermissionsPanel.test.tsx index af250a043ee..ff871b01e5c 100644 --- a/app/src/components/settings/panels/__tests__/PermissionsPanel.test.tsx +++ b/app/src/components/settings/panels/__tests__/PermissionsPanel.test.tsx @@ -30,6 +30,9 @@ const agentPaths = (overrides: Partial = {}): AgentPaths => ({ workspace_dir: '/home/test/.openhuman/users/u1/workspace', projects_dir: '/home/test/OpenHuman/projects', action_dir_source: 'default', + files_dir: '/home/test/OpenHuman/projects/Files', + default_files_dir: '/home/test/OpenHuman/projects/Files', + files_dir_source: 'default', ...overrides, }); diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.ts index db6eb5ff19a..8373bfe621e 100644 --- a/app/src/lib/i18n/ar.ts +++ b/app/src/lib/i18n/ar.ts @@ -5322,6 +5322,15 @@ const messages: TranslationMap = { 'settings.agentAccess.timeout.envOverride': 'متغير البيئة OPENHUMAN_TOOL_TIMEOUT_SECS يتجاوز هذا الإعداد، لذا لن يكون للتغييرات هنا أي تأثير حتى يتم إلغاء ضبطه.', 'settings.agentAccess.grantedFolders': 'الملفات الممنوحة', + 'settings.agentAccess.filesFolder.label': 'مجلد الملفات', + 'settings.agentAccess.filesFolder.desc': + 'المكان الذي تُحفظ فيه الملفات التي ينشئها الوكيل، مثل العروض التقديمية والمستندات والصور ومقاطع الفيديو. يسري التغيير على الملفات الجديدة؛ وتبقى الملفات الحالية في مكانها.', + 'settings.agentAccess.filesFolder.save': 'حفظ', + 'settings.agentAccess.filesFolder.reset': 'استخدام الافتراضي', + 'settings.agentAccess.filesFolder.saved': 'تم تحديث مجلد الملفات', + 'settings.agentAccess.filesFolder.loadError': 'تعذّر تحميل مجلد الملفات.', + 'settings.agentAccess.filesFolder.open': 'إظهار في المجلد', + 'settings.agentAccess.filesFolder.openError': 'تعذّر فتح مجلد الملفات.', 'settings.agentAccess.alwaysAllow': 'الأدوات المتدنية دائما', 'settings.agentAccess.alwaysAllowDesc': 'الأدوات التي وضعت علامة "الطرق تسمح" في الدردشة دون أن تسأل. أزيلي واحدة ليتم دفعها مجدداً', @@ -6290,6 +6299,7 @@ const messages: TranslationMap = { 'chat.files.error.resolve_failed': 'تعذّر تحديد الملف. حاول مرة أخرى.', 'chat.files.error.download_failed': 'فشل التنزيل. حاول مرة أخرى.', 'chat.files.error.delete_failed': 'تعذّر حذف الملف. حاول مرة أخرى.', + 'chat.files.error.reveal_failed': 'تعذّر عرض الملف. ربما نُقل أو حُذف خارج OpenHuman.', 'memory.tab.council': 'Council', 'activity.tabs.automations': 'أتمتة', 'activity.tabs.automationsDescription': diff --git a/app/src/lib/i18n/bn.ts b/app/src/lib/i18n/bn.ts index 67aef529866..60efa5373fd 100644 --- a/app/src/lib/i18n/bn.ts +++ b/app/src/lib/i18n/bn.ts @@ -5439,6 +5439,15 @@ const messages: TranslationMap = { 'settings.agentAccess.timeout.envOverride': 'OPENHUMAN_TOOL_TIMEOUT_SECS এনভায়রনমেন্ট ভেরিয়েবলটি এই সেটিং ওভাররাইড করছে, তাই এটি আনসেট না করা পর্যন্ত এখানে পরিবর্তনের কোনো প্রভাব পড়বে না।', 'settings.agentAccess.grantedFolders': 'ফোল্ডার', + 'settings.agentAccess.filesFolder.label': 'ফাইল ফোল্ডার', + 'settings.agentAccess.filesFolder.desc': + 'এজেন্ট যে ফাইলগুলো তৈরি করে, যেমন প্রেজেন্টেশন, ডকুমেন্ট, ছবি ও ভিডিও, সেগুলো এখানে সংরক্ষিত হয়। পরিবর্তন শুধু নতুন ফাইলে প্রযোজ্য; পুরোনো ফাইল যেখানে আছে সেখানেই থাকে।', + 'settings.agentAccess.filesFolder.save': 'সংরক্ষণ করুন', + 'settings.agentAccess.filesFolder.reset': 'ডিফল্ট ব্যবহার করুন', + 'settings.agentAccess.filesFolder.saved': 'ফাইল ফোল্ডার আপডেট হয়েছে', + 'settings.agentAccess.filesFolder.loadError': 'ফাইল ফোল্ডার লোড করা যায়নি।', + 'settings.agentAccess.filesFolder.open': 'ফোল্ডারে দেখান', + 'settings.agentAccess.filesFolder.openError': 'ফাইল ফোল্ডার খোলা যায়নি।', 'settings.agentAccess.alwaysAllow': 'সর্বদা অপসারণযোগ্য সরঞ্জাম', 'settings.agentAccess.alwaysAllowDesc': 'জিজ্ঞাসা না করে আলাপনের ক্ষেত্রে "সর্বদা" প্রয়োগ করা হবে। পুনরায় লেখার জন্য একটি ফোল্ডার মুছে ফেলা হবে।', @@ -6430,6 +6439,8 @@ const messages: TranslationMap = { 'chat.files.error.resolve_failed': 'আর্টিফ্যাক্ট সমাধান করা যায়নি। আবার চেষ্টা করুন।', 'chat.files.error.download_failed': 'ডাউনলোড ব্যর্থ হয়েছে। আবার চেষ্টা করুন।', 'chat.files.error.delete_failed': 'ফাইল মোছা যায়নি। আবার চেষ্টা করুন।', + 'chat.files.error.reveal_failed': + 'ফাইলটি দেখানো যায়নি। এটি হয়তো OpenHuman-এর বাইরে সরানো বা মুছে ফেলা হয়েছে।', 'memory.tab.council': 'Council', 'activity.tabs.automations': 'অটোমেশন', 'activity.tabs.automationsDescription': diff --git a/app/src/lib/i18n/de.ts b/app/src/lib/i18n/de.ts index 317a6beb17d..c3aabe1744b 100644 --- a/app/src/lib/i18n/de.ts +++ b/app/src/lib/i18n/de.ts @@ -5577,6 +5577,15 @@ const messages: TranslationMap = { 'settings.agentAccess.timeout.envOverride': 'Die Umgebungsvariable OPENHUMAN_TOOL_TIMEOUT_SECS überschreibt diese Einstellung, daher haben Änderungen hier keine Wirkung, bis sie entfernt wird.', 'settings.agentAccess.grantedFolders': 'Erteilte Ordner', + 'settings.agentAccess.filesFolder.label': 'Dateiordner', + 'settings.agentAccess.filesFolder.desc': + 'Hier speichert der Agent die Dateien, die er erstellt, etwa Präsentationen, Dokumente, Bilder und Videos. Eine Änderung gilt für neue Dateien; vorhandene Dateien bleiben, wo sie sind.', + 'settings.agentAccess.filesFolder.save': 'Speichern', + 'settings.agentAccess.filesFolder.reset': 'Standard verwenden', + 'settings.agentAccess.filesFolder.saved': 'Dateiordner aktualisiert', + 'settings.agentAccess.filesFolder.loadError': 'Der Dateiordner konnte nicht geladen werden.', + 'settings.agentAccess.filesFolder.open': 'Im Ordner anzeigen', + 'settings.agentAccess.filesFolder.openError': 'Der Dateiordner konnte nicht geöffnet werden.', 'settings.agentAccess.alwaysAllow': 'Immer erlaubte Werkzeuge', 'settings.agentAccess.alwaysAllowDesc': 'Tools, die Sie im Chatlauf ohne zu fragen als "Immer zulassen" markiert haben. Entfernen Sie eine, um erneut aufgefordert zu werden.', @@ -6589,6 +6598,8 @@ const messages: TranslationMap = { 'Das Artefakt konnte nicht aufgelöst werden. Bitte erneut versuchen.', 'chat.files.error.download_failed': 'Download fehlgeschlagen. Bitte erneut versuchen.', 'chat.files.error.delete_failed': 'Datei konnte nicht gelöscht werden. Bitte erneut versuchen.', + 'chat.files.error.reveal_failed': + 'Die Datei konnte nicht angezeigt werden. Sie wurde möglicherweise außerhalb von OpenHuman verschoben oder gelöscht.', 'memory.tab.council': 'Council', 'activity.tabs.automations': 'Automatisierungen', 'activity.tabs.automationsDescription': diff --git a/app/src/lib/i18n/en.ts b/app/src/lib/i18n/en.ts index 0389e667bf3..8d16d68052d 100644 --- a/app/src/lib/i18n/en.ts +++ b/app/src/lib/i18n/en.ts @@ -6236,6 +6236,15 @@ const en: TranslationMap = { 'settings.agentAccess.group.fileSystem': 'File system', 'settings.agentAccess.group.limits': 'Limits', 'settings.agentAccess.grantedFolders': 'Granted folders', + 'settings.agentAccess.filesFolder.label': 'Files folder', + 'settings.agentAccess.filesFolder.desc': + 'Where the files the agent makes, like decks, documents, images and videos, are saved. A change applies to new files; existing files stay where they are.', + 'settings.agentAccess.filesFolder.save': 'Save', + 'settings.agentAccess.filesFolder.reset': 'Use default', + 'settings.agentAccess.filesFolder.saved': 'Files folder updated', + 'settings.agentAccess.filesFolder.loadError': 'Could not load the files folder.', + 'settings.agentAccess.filesFolder.open': 'Show in folder', + 'settings.agentAccess.filesFolder.openError': 'Couldn’t open the files folder.', 'settings.agentAccess.alwaysAllow': 'Always-allowed tools', 'settings.agentAccess.alwaysAllowDesc': 'Tools you marked "Always allow" in chat run without asking. Remove one to be prompted again.', @@ -7293,6 +7302,8 @@ const en: TranslationMap = { 'chat.files.error.resolve_failed': 'Couldn’t resolve the artifact. Please try again.', 'chat.files.error.download_failed': 'Download failed. Please try again.', 'chat.files.error.delete_failed': 'Couldn’t delete the file. Please try again.', + 'chat.files.error.reveal_failed': + 'Couldn’t show the file. It may have been moved or deleted outside OpenHuman.', // First-run initialization (harness_init) 'harnessInit.title': 'Setting things up', diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.ts index 9b5913833f1..6f7dc166f6a 100644 --- a/app/src/lib/i18n/es.ts +++ b/app/src/lib/i18n/es.ts @@ -5532,6 +5532,15 @@ const messages: TranslationMap = { 'settings.agentAccess.timeout.envOverride': 'La variable de entorno OPENHUMAN_TOOL_TIMEOUT_SECS está anulando este ajuste, por lo que los cambios aquí no tendrán efecto hasta que se elimine.', 'settings.agentAccess.grantedFolders': 'Carpetas concedidas', + 'settings.agentAccess.filesFolder.label': 'Carpeta de archivos', + 'settings.agentAccess.filesFolder.desc': + 'Dónde se guardan los archivos que crea el agente, como presentaciones, documentos, imágenes y vídeos. El cambio se aplica a los archivos nuevos; los existentes se quedan donde están.', + 'settings.agentAccess.filesFolder.save': 'Guardar', + 'settings.agentAccess.filesFolder.reset': 'Usar la predeterminada', + 'settings.agentAccess.filesFolder.saved': 'Carpeta de archivos actualizada', + 'settings.agentAccess.filesFolder.loadError': 'No se pudo cargar la carpeta de archivos.', + 'settings.agentAccess.filesFolder.open': 'Mostrar en la carpeta', + 'settings.agentAccess.filesFolder.openError': 'No se pudo abrir la carpeta de archivos.', 'settings.agentAccess.alwaysAllow': 'Herramientas siempre permitidas', 'settings.agentAccess.alwaysAllowDesc': 'Las herramientas que marcaste como "Permitir siempre" en el chat se ejecutan sin pedir permiso. Elimina una para que se te pregunte nuevamente.', @@ -6552,6 +6561,8 @@ const messages: TranslationMap = { 'chat.files.error.resolve_failed': 'No se pudo resolver el artefacto. Inténtalo de nuevo.', 'chat.files.error.download_failed': 'La descarga falló. Inténtalo de nuevo.', 'chat.files.error.delete_failed': 'No se pudo eliminar el archivo. Inténtalo de nuevo.', + 'chat.files.error.reveal_failed': + 'No se pudo mostrar el archivo. Puede que se haya movido o eliminado fuera de OpenHuman.', 'memory.tab.council': 'Council', 'activity.tabs.automations': 'Automatizaciones', 'activity.tabs.automationsDescription': diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.ts index 9d490f73f95..35b845efbe7 100644 --- a/app/src/lib/i18n/fr.ts +++ b/app/src/lib/i18n/fr.ts @@ -5557,6 +5557,15 @@ const messages: TranslationMap = { 'settings.agentAccess.timeout.envOverride': "La variable d'environnement OPENHUMAN_TOOL_TIMEOUT_SECS remplace ce paramètre ; les modifications effectuées ici n'auront donc aucun effet tant qu'elle n'est pas supprimée.", 'settings.agentAccess.grantedFolders': 'Dossiers accordés', + 'settings.agentAccess.filesFolder.label': 'Dossier des fichiers', + 'settings.agentAccess.filesFolder.desc': + 'Emplacement où sont enregistrés les fichiers créés par l’agent, comme les présentations, documents, images et vidéos. Une modification s’applique aux nouveaux fichiers ; les fichiers existants restent où ils sont.', + 'settings.agentAccess.filesFolder.save': 'Enregistrer', + 'settings.agentAccess.filesFolder.reset': 'Utiliser le dossier par défaut', + 'settings.agentAccess.filesFolder.saved': 'Dossier des fichiers mis à jour', + 'settings.agentAccess.filesFolder.loadError': 'Impossible de charger le dossier des fichiers.', + 'settings.agentAccess.filesFolder.open': 'Afficher dans le dossier', + 'settings.agentAccess.filesFolder.openError': 'Impossible d’ouvrir le dossier des fichiers.', 'settings.agentAccess.alwaysAllow': 'Outils toujours autorisés', 'settings.agentAccess.alwaysAllowDesc': "Les outils que vous avez marqués « Toujours autoriser » dans le chat s'exécutent sans demander. Supprimez-en un pour être invité à nouveau.", @@ -6577,6 +6586,8 @@ const messages: TranslationMap = { 'chat.files.error.resolve_failed': 'Impossible de résoudre l’artefact. Réessayez.', 'chat.files.error.download_failed': 'Échec du téléchargement. Réessayez.', 'chat.files.error.delete_failed': 'Impossible de supprimer le fichier. Réessayez.', + 'chat.files.error.reveal_failed': + 'Impossible d’afficher le fichier. Il a peut-être été déplacé ou supprimé en dehors d’OpenHuman.', 'memory.tab.council': 'Council', 'activity.tabs.automations': 'Automatisations', 'activity.tabs.automationsDescription': diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.ts index 58581ab09e5..a755765dc9e 100644 --- a/app/src/lib/i18n/hi.ts +++ b/app/src/lib/i18n/hi.ts @@ -5442,6 +5442,15 @@ const messages: TranslationMap = { 'settings.agentAccess.timeout.envOverride': 'OPENHUMAN_TOOL_TIMEOUT_SECS एनवायरनमेंट वेरिएबल इस सेटिंग को ओवरराइड कर रहा है, इसलिए जब तक इसे अनसेट नहीं किया जाता, यहाँ किए गए बदलावों का कोई असर नहीं होगा।', 'settings.agentAccess.grantedFolders': 'स्वीकृत फ़ोल्डर', + 'settings.agentAccess.filesFolder.label': 'फ़ाइल फ़ोल्डर', + 'settings.agentAccess.filesFolder.desc': + 'एजेंट जो फ़ाइलें बनाता है, जैसे प्रेज़ेंटेशन, दस्तावेज़, चित्र और वीडियो, वे यहाँ सहेजी जाती हैं। बदलाव नई फ़ाइलों पर लागू होता है; मौजूदा फ़ाइलें जहाँ हैं वहीं रहती हैं।', + 'settings.agentAccess.filesFolder.save': 'सहेजें', + 'settings.agentAccess.filesFolder.reset': 'डिफ़ॉल्ट उपयोग करें', + 'settings.agentAccess.filesFolder.saved': 'फ़ाइल फ़ोल्डर अपडेट हो गया', + 'settings.agentAccess.filesFolder.loadError': 'फ़ाइल फ़ोल्डर लोड नहीं हो सका।', + 'settings.agentAccess.filesFolder.open': 'फ़ोल्डर में दिखाएँ', + 'settings.agentAccess.filesFolder.openError': 'फ़ाइल फ़ोल्डर नहीं खोला जा सका।', 'settings.agentAccess.alwaysAllow': 'हमेशा की अनुमति उपकरण', 'settings.agentAccess.alwaysAllowDesc': 'उपकरण जिन्हें आपने बिना पूछे चैट रन में "अलवे अनुमति" चिह्नित किया। एक बार फिर से शुरू करने के लिए।', @@ -6432,6 +6441,8 @@ const messages: TranslationMap = { 'chat.files.error.resolve_failed': 'आर्टिफैक्ट को हल नहीं किया जा सका। पुनः प्रयास करें।', 'chat.files.error.download_failed': 'डाउनलोड विफल रहा। पुनः प्रयास करें।', 'chat.files.error.delete_failed': 'फ़ाइल हटाई नहीं जा सकी। पुनः प्रयास करें।', + 'chat.files.error.reveal_failed': + 'फ़ाइल नहीं दिखाई जा सकी। हो सकता है कि इसे OpenHuman के बाहर हटाया या मिटाया गया हो।', 'memory.tab.council': 'Council', 'activity.tabs.automations': 'स्वचालन', 'activity.tabs.automationsDescription': diff --git a/app/src/lib/i18n/id.ts b/app/src/lib/i18n/id.ts index 51a0f9dfd2b..c15ac0dd193 100644 --- a/app/src/lib/i18n/id.ts +++ b/app/src/lib/i18n/id.ts @@ -5474,6 +5474,15 @@ const messages: TranslationMap = { 'settings.agentAccess.timeout.envOverride': 'Variabel lingkungan OPENHUMAN_TOOL_TIMEOUT_SECS menggantikan pengaturan ini, sehingga perubahan di sini tidak berpengaruh hingga variabel tersebut dihapus.', 'settings.agentAccess.grantedFolders': 'Folder yang diberikan', + 'settings.agentAccess.filesFolder.label': 'Folder file', + 'settings.agentAccess.filesFolder.desc': + 'Tempat menyimpan file yang dibuat agen, seperti presentasi, dokumen, gambar, dan video. Perubahan berlaku untuk file baru; file yang sudah ada tetap di tempatnya.', + 'settings.agentAccess.filesFolder.save': 'Simpan', + 'settings.agentAccess.filesFolder.reset': 'Gunakan bawaan', + 'settings.agentAccess.filesFolder.saved': 'Folder file diperbarui', + 'settings.agentAccess.filesFolder.loadError': 'Folder file tidak dapat dimuat.', + 'settings.agentAccess.filesFolder.open': 'Tampilkan di folder', + 'settings.agentAccess.filesFolder.openError': 'Folder file tidak dapat dibuka.', 'settings.agentAccess.alwaysAllow': 'Selalu-diperbolehkan alat', 'settings.agentAccess.alwaysAllowDesc': 'Perkakas yang Anda tandai "Always allow" dalam run percakapan tanpa bertanya. Hapus satu yang akan diminta lagi.', @@ -6466,6 +6475,8 @@ const messages: TranslationMap = { 'chat.files.error.resolve_failed': 'Tidak dapat memuat artefak. Coba lagi.', 'chat.files.error.download_failed': 'Unduhan gagal. Coba lagi.', 'chat.files.error.delete_failed': 'Tidak bisa menghapus file. Coba lagi.', + 'chat.files.error.reveal_failed': + 'File tidak dapat ditampilkan. File mungkin telah dipindahkan atau dihapus di luar OpenHuman.', 'memory.tab.council': 'Council', 'activity.tabs.automations': 'Otomatisasi', 'activity.tabs.automationsDescription': diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.ts index bfff829d71f..3a140616467 100644 --- a/app/src/lib/i18n/it.ts +++ b/app/src/lib/i18n/it.ts @@ -5523,6 +5523,15 @@ const messages: TranslationMap = { 'settings.agentAccess.timeout.envOverride': "La variabile d'ambiente OPENHUMAN_TOOL_TIMEOUT_SECS sta sovrascrivendo questa impostazione, quindi le modifiche qui non avranno effetto finché non viene rimossa.", 'settings.agentAccess.grantedFolders': 'Cartelle concesse', + 'settings.agentAccess.filesFolder.label': 'Cartella dei file', + 'settings.agentAccess.filesFolder.desc': + 'Dove vengono salvati i file creati dall’agente, come presentazioni, documenti, immagini e video. La modifica vale per i nuovi file; quelli esistenti restano dove sono.', + 'settings.agentAccess.filesFolder.save': 'Salva', + 'settings.agentAccess.filesFolder.reset': 'Usa quella predefinita', + 'settings.agentAccess.filesFolder.saved': 'Cartella dei file aggiornata', + 'settings.agentAccess.filesFolder.loadError': 'Impossibile caricare la cartella dei file.', + 'settings.agentAccess.filesFolder.open': 'Mostra nella cartella', + 'settings.agentAccess.filesFolder.openError': 'Impossibile aprire la cartella dei file.', 'settings.agentAccess.alwaysAllow': 'Strumenti sempre consentiti', 'settings.agentAccess.alwaysAllowDesc': 'Gli strumenti che hai contrassegnato come "Consenti sempre" in chat funzionano senza chiedere. Rimuovine uno per ricevere nuovamente la richiesta.', @@ -6534,6 +6543,8 @@ const messages: TranslationMap = { 'chat.files.error.resolve_failed': 'Impossibile risolvere l’artefatto. Riprova.', 'chat.files.error.download_failed': 'Download non riuscito. Riprova.', 'chat.files.error.delete_failed': 'Impossibile eliminare il file. Riprova.', + 'chat.files.error.reveal_failed': + 'Impossibile mostrare il file. Potrebbe essere stato spostato o eliminato al di fuori di OpenHuman.', 'memory.tab.council': 'Council', 'activity.tabs.automations': 'Automazioni', 'activity.tabs.automationsDescription': diff --git a/app/src/lib/i18n/ko.ts b/app/src/lib/i18n/ko.ts index 1a70f50b9a3..c6648196a59 100644 --- a/app/src/lib/i18n/ko.ts +++ b/app/src/lib/i18n/ko.ts @@ -5382,6 +5382,15 @@ const messages: TranslationMap = { 'settings.agentAccess.timeout.envOverride': 'OPENHUMAN_TOOL_TIMEOUT_SECS 환경 변수가 이 설정을 재정의하고 있으므로, 해당 변수를 해제하기 전까지 여기서의 변경 사항은 적용되지 않습니다.', 'settings.agentAccess.grantedFolders': '허용된 폴더', + 'settings.agentAccess.filesFolder.label': '파일 폴더', + 'settings.agentAccess.filesFolder.desc': + '에이전트가 만드는 프레젠테이션, 문서, 이미지, 동영상 같은 파일이 저장되는 위치입니다. 변경 사항은 새 파일에 적용되며, 기존 파일은 그대로 유지됩니다.', + 'settings.agentAccess.filesFolder.save': '저장', + 'settings.agentAccess.filesFolder.reset': '기본값 사용', + 'settings.agentAccess.filesFolder.saved': '파일 폴더가 업데이트되었습니다', + 'settings.agentAccess.filesFolder.loadError': '파일 폴더를 불러올 수 없습니다.', + 'settings.agentAccess.filesFolder.open': '폴더에서 보기', + 'settings.agentAccess.filesFolder.openError': '파일 폴더를 열 수 없습니다.', 'settings.agentAccess.alwaysAllow': '항상 허용된 도구', 'settings.agentAccess.alwaysAllowDesc': '채팅에서 "항상 허용"으로 표시한 도구는 확인 없이 실행됩니다. 다시 확인을 받으려면 항목을 제거하세요.', @@ -6359,6 +6368,8 @@ const messages: TranslationMap = { 'chat.files.error.resolve_failed': '아티팩트를 해석할 수 없습니다. 다시 시도해주세요.', 'chat.files.error.download_failed': '다운로드에 실패했습니다. 다시 시도해주세요.', 'chat.files.error.delete_failed': '파일을 삭제하지 못했습니다. 다시 시도해주세요.', + 'chat.files.error.reveal_failed': + '파일을 표시할 수 없습니다. OpenHuman 외부에서 이동되었거나 삭제되었을 수 있습니다.', 'memory.tab.council': 'Council', 'activity.tabs.automations': '자동화', 'activity.tabs.automationsDescription': diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.ts index 282f63b12fa..fc8494c48b5 100644 --- a/app/src/lib/i18n/pl.ts +++ b/app/src/lib/i18n/pl.ts @@ -5517,6 +5517,15 @@ const messages: TranslationMap = { 'settings.agentAccess.timeout.envOverride': 'Zmienna środowiskowa OPENHUMAN_TOOL_TIMEOUT_SECS zastępuje to ustawienie, więc zmiany tutaj nie odniosą skutku, dopóki nie zostanie ona usunięta.', 'settings.agentAccess.grantedFolders': 'Przyznane foldery', + 'settings.agentAccess.filesFolder.label': 'Folder plików', + 'settings.agentAccess.filesFolder.desc': + 'Miejsce, w którym zapisywane są pliki tworzone przez agenta, takie jak prezentacje, dokumenty, obrazy i filmy. Zmiana dotyczy nowych plików; istniejące pliki pozostają na miejscu.', + 'settings.agentAccess.filesFolder.save': 'Zapisz', + 'settings.agentAccess.filesFolder.reset': 'Użyj domyślnego', + 'settings.agentAccess.filesFolder.saved': 'Zaktualizowano folder plików', + 'settings.agentAccess.filesFolder.loadError': 'Nie udało się wczytać folderu plików.', + 'settings.agentAccess.filesFolder.open': 'Pokaż w folderze', + 'settings.agentAccess.filesFolder.openError': 'Nie udało się otworzyć folderu plików.', 'settings.agentAccess.alwaysAllow': 'Zawsze dozwolone narzędzia', 'settings.agentAccess.alwaysAllowDesc': 'Narzędzia oznaczone w czacie jako „Zawsze zezwalaj” działają bez pytania. Usuń narzędzie, aby znów wymagało potwierdzenia.', @@ -6577,6 +6586,8 @@ const messages: TranslationMap = { 'Nie udało się odnaleźć artefaktu. Prosimy spróbować ponownie.', 'chat.files.error.download_failed': 'Pobieranie nie powiodło się. Prosimy spróbować ponownie.', 'chat.files.error.delete_failed': 'Nie udało się usunąć pliku. Prosimy spróbować ponownie.', + 'chat.files.error.reveal_failed': + 'Nie udało się pokazać pliku. Mógł zostać przeniesiony lub usunięty poza OpenHuman.', 'harnessInit.title': 'Trwa konfiguracja', diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.ts index cd98ddb6dc3..05d43d9207f 100644 --- a/app/src/lib/i18n/pt.ts +++ b/app/src/lib/i18n/pt.ts @@ -5517,6 +5517,15 @@ const messages: TranslationMap = { 'settings.agentAccess.timeout.envOverride': 'A variável de ambiente OPENHUMAN_TOOL_TIMEOUT_SECS está substituindo esta configuração, portanto as alterações aqui não terão efeito até que ela seja removida.', 'settings.agentAccess.grantedFolders': 'Pastas concedidas', + 'settings.agentAccess.filesFolder.label': 'Pasta de arquivos', + 'settings.agentAccess.filesFolder.desc': + 'Onde são salvos os arquivos que o agente cria, como apresentações, documentos, imagens e vídeos. A alteração vale para arquivos novos; os existentes permanecem onde estão.', + 'settings.agentAccess.filesFolder.save': 'Salvar', + 'settings.agentAccess.filesFolder.reset': 'Usar a padrão', + 'settings.agentAccess.filesFolder.saved': 'Pasta de arquivos atualizada', + 'settings.agentAccess.filesFolder.loadError': 'Não foi possível carregar a pasta de arquivos.', + 'settings.agentAccess.filesFolder.open': 'Mostrar na pasta', + 'settings.agentAccess.filesFolder.openError': 'Não foi possível abrir a pasta de arquivos.', 'settings.agentAccess.alwaysAllow': 'Ferramentas sempre permitidas', 'settings.agentAccess.alwaysAllowDesc': 'As ferramentas que você marcou como "Sempre permitir" no chat funcionam sem perguntar. Remova uma para ser solicitado novamente.', @@ -6524,6 +6533,8 @@ const messages: TranslationMap = { 'chat.files.error.resolve_failed': 'Não foi possível resolver o artefato. Tente novamente.', 'chat.files.error.download_failed': 'O download falhou. Tente novamente.', 'chat.files.error.delete_failed': 'Não foi possível excluir o arquivo. Tente novamente.', + 'chat.files.error.reveal_failed': + 'Não foi possível mostrar o arquivo. Ele pode ter sido movido ou excluído fora do OpenHuman.', 'memory.tab.council': 'Council', 'activity.tabs.automations': 'Automações', 'activity.tabs.automationsDescription': diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.ts index e0901bd4bfa..302b3b01c63 100644 --- a/app/src/lib/i18n/ru.ts +++ b/app/src/lib/i18n/ru.ts @@ -5488,6 +5488,15 @@ const messages: TranslationMap = { 'settings.agentAccess.timeout.envOverride': 'Переменная окружения OPENHUMAN_TOOL_TIMEOUT_SECS переопределяет эту настройку, поэтому изменения здесь не вступят в силу, пока она не будет сброшена.', 'settings.agentAccess.grantedFolders': 'Предоставленные папки', + 'settings.agentAccess.filesFolder.label': 'Папка файлов', + 'settings.agentAccess.filesFolder.desc': + 'Куда сохраняются файлы, которые создаёт агент: презентации, документы, изображения и видео. Изменение применяется к новым файлам; существующие остаются на месте.', + 'settings.agentAccess.filesFolder.save': 'Сохранить', + 'settings.agentAccess.filesFolder.reset': 'Использовать по умолчанию', + 'settings.agentAccess.filesFolder.saved': 'Папка файлов обновлена', + 'settings.agentAccess.filesFolder.loadError': 'Не удалось загрузить папку файлов.', + 'settings.agentAccess.filesFolder.open': 'Показать в папке', + 'settings.agentAccess.filesFolder.openError': 'Не удалось открыть папку файлов.', 'settings.agentAccess.alwaysAllow': 'Всегда разрешенные инструменты', 'settings.agentAccess.alwaysAllowDesc': 'Инструменты, которые вы отметили в чате как «Всегда разрешать», запускаются без запроса. Удалите один, чтобы запрос появился снова.', @@ -6488,6 +6497,8 @@ const messages: TranslationMap = { 'chat.files.error.resolve_failed': 'Не удалось получить артефакт. Попробуйте ещё раз.', 'chat.files.error.download_failed': 'Не удалось загрузить файл. Попробуйте ещё раз.', 'chat.files.error.delete_failed': 'Не удалось удалить файл. Попробуйте ещё раз.', + 'chat.files.error.reveal_failed': + 'Не удалось показать файл. Возможно, он был перемещён или удалён вне OpenHuman.', 'memory.tab.council': 'Council', 'activity.tabs.automations': 'Автоматизации', 'activity.tabs.automationsDescription': diff --git a/app/src/lib/i18n/zh-CN.ts b/app/src/lib/i18n/zh-CN.ts index dcada1aff35..59dce2efc32 100644 --- a/app/src/lib/i18n/zh-CN.ts +++ b/app/src/lib/i18n/zh-CN.ts @@ -5154,6 +5154,15 @@ const messages: TranslationMap = { 'settings.agentAccess.timeout.envOverride': '环境变量 OPENHUMAN_TOOL_TIMEOUT_SECS 正在覆盖此设置,因此在取消该变量之前,此处的更改不会生效。', 'settings.agentAccess.grantedFolders': '已授权文件夹', + 'settings.agentAccess.filesFolder.label': '文件保存文件夹', + 'settings.agentAccess.filesFolder.desc': + '智能体生成的文件(如演示文稿、文档、图片和视频)保存在这里。更改仅对新文件生效;现有文件保持原位。', + 'settings.agentAccess.filesFolder.save': '保存', + 'settings.agentAccess.filesFolder.reset': '使用默认文件夹', + 'settings.agentAccess.filesFolder.saved': '文件保存文件夹已更新', + 'settings.agentAccess.filesFolder.loadError': '无法加载文件保存文件夹。', + 'settings.agentAccess.filesFolder.open': '在文件夹中显示', + 'settings.agentAccess.filesFolder.openError': '无法打开文件保存文件夹。', 'settings.agentAccess.alwaysAllow': '始终允许的工具', 'settings.agentAccess.alwaysAllowDesc': '你在聊天中标记为“始终允许”的工具会直接运行且不再询问。移除后会重新提示。', @@ -6088,6 +6097,7 @@ const messages: TranslationMap = { 'chat.files.error.resolve_failed': '无法解析 artifact。请重试。', 'chat.files.error.download_failed': '下载失败。请重试。', 'chat.files.error.delete_failed': '无法删除文件。请重试。', + 'chat.files.error.reveal_failed': '无法显示该文件。它可能已在 OpenHuman 之外被移动或删除。', 'memory.tab.council': 'Council', 'activity.tabs.automations': '自动化', 'activity.tabs.automationsDescription': '可复用、可运行的流程:目标及达成目标的步骤。', diff --git a/app/src/pages/Brain.tsx b/app/src/pages/Brain.tsx index b5d3955966a..01e9fbe06c4 100644 --- a/app/src/pages/Brain.tsx +++ b/app/src/pages/Brain.tsx @@ -435,7 +435,10 @@ export default function Brain() { {activeTab === 'sources' && (
- + {/* Coding sessions are a family of their own: an engine + can accept synced items without reading local agent + transcripts (hosted memory does exactly that). */} + @@ -446,10 +449,14 @@ export default function Brain() { {activeTab === 'sync' && syncView === 'status' && (
+ {/* The ingest pipeline's status is the local chunk store's: + hosted memory draws a tree but keeps no such store. */} - - - + + + + + {/* openhuman#6257: what is syncing right now, beside the history of what already ran. */} diff --git a/app/src/pages/__tests__/Brain.test.tsx b/app/src/pages/__tests__/Brain.test.tsx index b3b9e946456..9b8819e193c 100644 --- a/app/src/pages/__tests__/Brain.test.tsx +++ b/app/src/pages/__tests__/Brain.test.tsx @@ -200,18 +200,18 @@ describe('Brain page', () => { expect(screen.queryByTestId('brain-sync-activity-card')).toBeNull(); }); - // A remote engine without the Sources family (hosted CortexDB) has no + // A remote engine without the Sources family (a direct CortexDB) has no // `memory_sources.*` RPCs at all: the sync panels must say so rather than // render and fail. it('shows the sync panels as unavailable on an engine without sources', async () => { graphExportMock.mockResolvedValue(makeGraph(0)); - engineMock.get.mockResolvedValue({ driver: 'tinyhumans' }); + engineMock.get.mockResolvedValue({ driver: 'cortex' }); engineMock.list.mockResolvedValue({ - active: 'tinyhumans', + active: 'cortex', engines: [ { - id: 'tinyhumans', - label: 'CortexDB (via TinyHumans)', + id: 'cortex', + label: 'CortexDB', capabilities: ['core', 'recall', 'portability', 'answer'], }, ], @@ -225,4 +225,75 @@ describe('Brain page', () => { expect(screen.queryByTestId('brain-sync-activity')).toBeNull(); expect(screen.queryByTestId('brain-sync-activity-card')).toBeNull(); }); + + // Hosted memory serves a tree — the server's understanding — but keeps no + // local chunk store: the graph draws, and the ingest pipeline's status panel + // says it is not available rather than reading a store that is not there. + const hostedWithTree = () => { + engineMock.get.mockResolvedValue({ driver: 'tinyhumans' }); + engineMock.list.mockResolvedValue({ + active: 'tinyhumans', + engines: [ + { + id: 'tinyhumans', + label: 'CortexDB (via TinyHumans)', + capabilities: ['core', 'recall', 'portability', 'sources', 'retrieval', 'tree'], + }, + ], + }); + }; + + it('draws the graph on hosted memory', async () => { + graphExportMock.mockResolvedValue(makeGraph(2)); + hostedWithTree(); + await act(async () => { + renderWithProviders(, { initialEntries: ['/?tab=graph'] }); + }); + await waitFor(() => { + expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:2'); + }); + }); + + it('gates the local pipeline status on hosted memory', async () => { + graphExportMock.mockResolvedValue(makeGraph(0)); + hostedWithTree(); + await act(async () => { + renderWithProviders(, { initialEntries: ['/?tab=sync'] }); + }); + await waitFor(() => { + const gated = screen + .getAllByTestId('memory-family-unavailable') + .map(node => node.getAttribute('data-family')); + expect(gated).toContain('chunks'); + }); + expect(screen.queryByTestId('brain-sync')).toBeNull(); + }); + + // Hosted memory accepts synced items but reads no local agent transcripts: + // the sources registry renders, the coding-sessions card says it is not + // available instead of calling an RPC the engine refuses. + it('gates the coding sessions card on its own family', async () => { + graphExportMock.mockResolvedValue(makeGraph(0)); + engineMock.get.mockResolvedValue({ driver: 'tinyhumans' }); + engineMock.list.mockResolvedValue({ + active: 'tinyhumans', + engines: [ + { + id: 'tinyhumans', + label: 'CortexDB (via TinyHumans)', + capabilities: ['core', 'recall', 'portability', 'answer', 'sources', 'documents'], + }, + ], + }); + await act(async () => { + renderWithProviders(, { initialEntries: ['/?tab=sources'] }); + }); + await waitFor(() => { + const gated = screen + .getAllByTestId('memory-family-unavailable') + .map(node => node.getAttribute('data-family')); + expect(gated).toContain('coding_sessions'); + expect(gated).not.toContain('sources'); + }); + }); }); diff --git a/app/src/pages/__tests__/Conversations.auiComposerSurfaces.test.tsx b/app/src/pages/__tests__/Conversations.auiComposerSurfaces.test.tsx index 64f967b2671..05cf2f3cb48 100644 --- a/app/src/pages/__tests__/Conversations.auiComposerSurfaces.test.tsx +++ b/app/src/pages/__tests__/Conversations.auiComposerSurfaces.test.tsx @@ -129,7 +129,7 @@ vi.mock('../../utils/openUrl', () => ({ openUrl: vi.fn() })); vi.mock('../../services/artifactDownloadService', () => ({ listArtifactsForThread: vi.fn().mockResolvedValue({ ok: true, artifacts: [] }), saveArtifactViaDialog: vi.fn(), - revealArtifactInFileManager: vi.fn(), + revealArtifact: vi.fn(), })); vi.mock('../../services/coreRpcClient', async orig => { diff --git a/app/src/services/__tests__/artifactDownloadService.test.ts b/app/src/services/__tests__/artifactDownloadService.test.ts index 74123888850..e179ee1d422 100644 --- a/app/src/services/__tests__/artifactDownloadService.test.ts +++ b/app/src/services/__tests__/artifactDownloadService.test.ts @@ -2,13 +2,13 @@ * artifactDownloadService coverage (#3024). * * Exercises every branch of `downloadArtifact`, `deleteArtifact`, and - * `revealArtifactInFileManager` — including the typed error-code + * `revealArtifact` — including the typed error-code * payloads, the title double-extension guard, and the non-Tauri / * empty-id / RPC-error / invoke-error paths. * * Mocks: `safeInvoke` + `isTauri` from `utils/tauriCommands/common`, - * `callCoreRpc` from `services/coreRpcClient`, and `revealItemInDir` - * from `@tauri-apps/plugin-opener`. The service has no other I/O. + * `callCoreRpc` from `services/coreRpcClient`, and `revealPath` from + * `utils/openUrl`. The service has no other I/O. */ import { beforeEach, describe, expect, it, vi } from 'vitest'; @@ -16,7 +16,7 @@ import { deleteArtifact, downloadArtifact, listArtifactsForThread, - revealArtifactInFileManager, + revealArtifact, saveArtifactViaDialog, } from '../artifactDownloadService'; import { callCoreRpc } from '../coreRpcClient'; @@ -24,7 +24,7 @@ import { callCoreRpc } from '../coreRpcClient'; const hoisted = vi.hoisted(() => ({ invoke: vi.fn(), isTauri: vi.fn(() => true), - revealItemInDir: vi.fn(), + revealPath: vi.fn(), })); vi.mock('../../utils/tauriCommands/common', () => ({ @@ -34,8 +34,8 @@ vi.mock('../../utils/tauriCommands/common', () => ({ vi.mock('../coreRpcClient', () => ({ callCoreRpc: vi.fn() })); -vi.mock('@tauri-apps/plugin-opener', () => ({ - revealItemInDir: (...args: unknown[]) => hoisted.revealItemInDir(...args), +vi.mock('../../utils/openUrl', () => ({ + revealPath: (...args: unknown[]) => hoisted.revealPath(...args), })); describe('listArtifactsForThread', () => { @@ -234,7 +234,7 @@ describe('downloadArtifact', () => { const outcome = await downloadArtifact('art-1', 'fallback-title', 'pptx'); expect(outcome).toEqual({ ok: true, path: '/Users/me/Downloads/climate-deck.pptx' }); expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', { - sourcePath: '/workspace/artifacts/art-1/deck.pptx', + artifactId: 'art-1', filename: 'climate-deck.pptx', }); }); @@ -247,7 +247,7 @@ describe('downloadArtifact', () => { hoisted.invoke.mockResolvedValueOnce('/dest/file.pdf'); await downloadArtifact('art-1', 'caller-fallback', 'pdf'); expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', { - sourcePath: '/p/file', + artifactId: 'art-1', filename: 'caller-fallback.pdf', }); }); @@ -257,7 +257,7 @@ describe('downloadArtifact', () => { hoisted.invoke.mockResolvedValueOnce('/dest/x'); await downloadArtifact('art-1', ' ', 'bin'); expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', { - sourcePath: '/p/file', + artifactId: 'art-1', filename: 'artifact.bin', }); }); @@ -270,7 +270,7 @@ describe('downloadArtifact', () => { hoisted.invoke.mockResolvedValueOnce('/dest/deck.pptx'); await downloadArtifact('art-1', 'deck', '...pptx'); expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', { - sourcePath: '/p/file', + artifactId: 'art-1', filename: 'deck.pptx', }); }); @@ -283,7 +283,7 @@ describe('downloadArtifact', () => { hoisted.invoke.mockResolvedValueOnce('/dest/deck.pptx'); await downloadArtifact('art-1', 'deck.pptx', 'pptx'); expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', { - sourcePath: '/p/file', + artifactId: 'art-1', filename: 'deck.pptx', }); }); @@ -296,7 +296,7 @@ describe('downloadArtifact', () => { hoisted.invoke.mockResolvedValueOnce('/dest/x'); await downloadArtifact('art-1', 'DECK.PPTX', 'pptx'); expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', { - sourcePath: '/p/file', + artifactId: 'art-1', filename: 'DECK.PPTX', }); }); @@ -311,7 +311,7 @@ describe('downloadArtifact', () => { hoisted.invoke.mockResolvedValueOnce('/dest/x'); await downloadArtifact('art-1', 'deck.pdf', 'pptx'); expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', { - sourcePath: '/p/file', + artifactId: 'art-1', filename: 'deck.pdf', }); }); @@ -324,7 +324,7 @@ describe('downloadArtifact', () => { hoisted.invoke.mockResolvedValueOnce('/dest/climate-overview.pptx'); await downloadArtifact('art-1', 'climate-overview', 'pptx'); expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', { - sourcePath: '/p/file', + artifactId: 'art-1', filename: 'climate-overview.pptx', }); }); @@ -337,7 +337,7 @@ describe('downloadArtifact', () => { hoisted.invoke.mockResolvedValueOnce('/dest/just-a-title'); await downloadArtifact('art-1', 'just-a-title', ''); expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', { - sourcePath: '/p/file', + artifactId: 'art-1', filename: 'just-a-title', }); }); @@ -402,38 +402,58 @@ describe('deleteArtifact', () => { }); }); -describe('revealArtifactInFileManager', () => { +describe('revealArtifact', () => { beforeEach(() => { vi.clearAllMocks(); hoisted.isTauri.mockReturnValue(true); }); - it('returns false when outside Tauri (no plugin call)', async () => { + it('needs the desktop app', async () => { hoisted.isTauri.mockReturnValueOnce(false); - const ok = await revealArtifactInFileManager('/some/path'); - expect(ok).toBe(false); - expect(hoisted.revealItemInDir).not.toHaveBeenCalled(); + const outcome = await revealArtifact('art-1'); + expect(outcome).toEqual(expect.objectContaining({ ok: false, code: 'NOT_DESKTOP' })); + expect(callCoreRpc).not.toHaveBeenCalled(); + expect(hoisted.revealPath).not.toHaveBeenCalled(); }); - it('returns false for an empty / whitespace path', async () => { - const ok = await revealArtifactInFileManager(' '); - expect(ok).toBe(false); - expect(hoisted.revealItemInDir).not.toHaveBeenCalled(); + it('reveals the real file the core reports, not a Downloads copy', async () => { + vi.mocked(callCoreRpc).mockResolvedValueOnce({ + absolute_path: '/Users/me/OpenHuman/projects/Files/deck.pptx', + }); + hoisted.revealPath.mockResolvedValueOnce(undefined); + + const outcome = await revealArtifact('art-1'); + + expect(outcome).toEqual({ ok: true }); + expect(callCoreRpc).toHaveBeenCalledWith({ + method: 'openhuman.ai_get_artifact', + params: { artifact_id: 'art-1' }, + }); + expect(hoisted.revealPath).toHaveBeenCalledWith('/Users/me/OpenHuman/projects/Files/deck.pptx'); }); - it('delegates to revealItemInDir on success', async () => { - hoisted.revealItemInDir.mockResolvedValueOnce(undefined); - const ok = await revealArtifactInFileManager('/Users/me/Downloads/deck.pptx'); - expect(ok).toBe(true); - expect(hoisted.revealItemInDir).toHaveBeenCalledWith('/Users/me/Downloads/deck.pptx'); + it('reports a file the core cannot resolve (e.g. moved or deleted)', async () => { + vi.mocked(callCoreRpc).mockRejectedValueOnce(new Error('file missing for id=art-1')); + const outcome = await revealArtifact('art-1'); + expect(outcome).toEqual({ + ok: false, + code: 'RESOLVE_FAILED', + error: 'file missing for id=art-1', + }); + expect(hoisted.revealPath).not.toHaveBeenCalled(); }); - it('swallows plugin errors and returns false (best-effort reveal)', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); - hoisted.revealItemInDir.mockRejectedValueOnce(new Error('plugin failed')); - const ok = await revealArtifactInFileManager('/Users/me/Downloads/deck.pptx'); - expect(ok).toBe(false); - warn.mockRestore(); + it('reports a file manager that refuses the path', async () => { + vi.mocked(callCoreRpc).mockResolvedValueOnce({ absolute_path: 'C:\\Users\\x\\deck.pptx' }); + hoisted.revealPath.mockRejectedValueOnce(new Error('path on another OS')); + const outcome = await revealArtifact('art-1'); + expect(outcome).toEqual({ ok: false, code: 'REVEAL_FAILED', error: 'path on another OS' }); + }); + + it('rejects an empty id without calling the core', async () => { + const outcome = await revealArtifact(' '); + expect(outcome).toEqual(expect.objectContaining({ ok: false, code: 'MISSING_ARTIFACT_ID' })); + expect(callCoreRpc).not.toHaveBeenCalled(); }); }); @@ -468,7 +488,7 @@ describe('saveArtifactViaDialog (dialog removed with rfd)', () => { const outcome = await saveArtifactViaDialog('a-1', 'Deck', 'pptx'); expect(outcome).toEqual({ ok: true, path: '/Users/me/Downloads/Deck.pptx' }); expect(hoisted.invoke).toHaveBeenCalledWith('download_artifact_to_downloads', { - sourcePath: '/ws/artifacts/a-1/deck.pptx', + artifactId: 'a-1', filename: 'Deck.pptx', }); // The removed `rfd` command must never be invoked again. diff --git a/app/src/services/artifactDownloadService.ts b/app/src/services/artifactDownloadService.ts index 6344d39273a..294955026a1 100644 --- a/app/src/services/artifactDownloadService.ts +++ b/app/src/services/artifactDownloadService.ts @@ -1,11 +1,14 @@ /** * Artifact export service (#2779). * - * All paths first resolve the artifact's absolute on-disk path + meta - * via the `openhuman.ai_get_artifact` core RPC, then hand a source path - * + filename hint to the `download_artifact_to_downloads` Tauri command, - * which copies into the user's Downloads directory with a non-colliding - * name and returns the dest path so the UI can offer "Reveal in Finder". + * All paths first resolve the artifact's meta via the + * `openhuman.ai_get_artifact` core RPC (which also reports a file moved or + * deleted outside OpenHuman), then hand the artifact id + filename hint to + * the `download_artifact_to_downloads` Tauri command. The shell resolves the + * id through the core's artifact store itself — it never trusts a + * renderer-supplied path (#5505) — copies into the user's Downloads directory + * with a non-colliding name, and returns the dest path so the UI can offer + * "Reveal in Finder". * * {@link saveArtifactViaDialog} is kept as the name its callers use, but * the native Save-As dialog behind it was removed with the shell's `rfd` @@ -16,8 +19,7 @@ * No-ops outside Tauri (browser dev preview) — export only makes sense in * the desktop shell. */ -import { revealItemInDir } from '@tauri-apps/plugin-opener'; - +import { revealPath } from '../utils/openUrl'; import { safeInvoke as invoke, isTauri } from '../utils/tauriCommands/common'; import { callCoreRpc } from './coreRpcClient'; @@ -36,7 +38,8 @@ export type ArtifactErrorCode = | 'RESOLVE_FAILED' | 'DOWNLOAD_FAILED' | 'CANCELLED' - | 'DELETE_FAILED'; + | 'DELETE_FAILED' + | 'REVEAL_FAILED'; /** Outcome surfaced to the UI for a single download attempt. */ interface DownloadArtifactOutcome { @@ -247,7 +250,7 @@ export async function downloadArtifact( try { const dest = await invoke('download_artifact_to_downloads', { - sourcePath: resolved.sourcePath, + artifactId, filename: resolved.filename, }); return { ok: true, path: dest }; @@ -308,19 +311,31 @@ export async function deleteArtifact(artifactId: string): Promise { - if (!isTauri()) return false; - if (!absolutePath.trim()) return false; +/** Outcome of a "Show in folder" request. */ +export type RevealArtifactOutcome = + | { ok: true } + | { ok: false; code: ArtifactErrorCode; error: string }; + +/** + * Open the OS file manager at an artifact's file (#5505). The file lives in + * the visible files folder (`~/OpenHuman/projects/Files` by default), so this + * shows the real file, not a Downloads copy. The path comes from the core + * (`ai_get_artifact`), which also reports a file moved or deleted outside + * OpenHuman; `revealPath` refuses a path from a core running on another OS. + */ +export async function revealArtifact(artifactId: string): Promise { + if (!isTauri()) { + return { ok: false, code: 'NOT_DESKTOP', error: 'Show in folder needs the desktop app' }; + } + const resolved = await resolveArtifactForExport(artifactId, '', ''); + if (!resolved.ok) { + return { ok: false, code: resolved.code, error: resolved.error }; + } try { - // Use the plugin's typed binding — the raw `invoke('plugin:opener| - // reveal_item_in_dir', { path })` shape silently no-ops because the - // plugin expects `{ paths: [absolutePath] }` (array). The binding - // handles the wrap. - await revealItemInDir(absolutePath); - return true; + await revealPath(resolved.sourcePath); + return { ok: true }; } catch (err) { - // Swallow — reveal is best-effort, the file is already saved. - console.warn('[artifact] revealItemInDir failed:', err); - return false; + const reason = err instanceof Error ? err.message : String(err); + return { ok: false, code: 'REVEAL_FAILED', error: reason }; } } diff --git a/app/src/services/chatService.ts b/app/src/services/chatService.ts index a72769c86a6..9bd526f8e6b 100644 --- a/app/src/services/chatService.ts +++ b/app/src/services/chatService.ts @@ -479,7 +479,7 @@ export interface ArtifactReadyEvent { * wrong `/artifacts/` tree after a workspace switch. */ workspace_dir: string; - /** Relative path under `/artifacts/`, e.g. `/deck.pptx`. */ + /** File name relative to its root: `deck.pptx` in the visible files folder, or `/deck.pptx` for a legacy record. */ path: string; /** Final on-disk size in bytes. */ size_bytes: number; @@ -527,7 +527,7 @@ export interface ArtifactPendingEvent { title: string; /** Absolute workspace root — see {@link ArtifactReadyEvent.workspace_dir}. */ workspace_dir: string; - /** Relative path under `/artifacts/`, e.g. `/deck.pptx`. */ + /** File name relative to its root: `deck.pptx` in the visible files folder, or `/deck.pptx` for a legacy record. */ path: string; /** See {@link ArtifactReadyEvent.tool_call_id}. */ tool_call_id?: string; diff --git a/app/src/store/chatRuntimeSlice.ts b/app/src/store/chatRuntimeSlice.ts index 429f390e146..7d37f728971 100644 --- a/app/src/store/chatRuntimeSlice.ts +++ b/app/src/store/chatRuntimeSlice.ts @@ -775,7 +775,7 @@ export interface ArtifactSnapshot { status: ArtifactStatus; /** Final on-disk size. Only set when `status === 'ready'`. */ sizeBytes?: number; - /** Relative path under `/artifacts/`. Only set when `status === 'ready'`. */ + /** File name relative to its root folder. Only set when `status === 'ready'`. */ path?: string; /** Producer-supplied reason. Only set when `status === 'failed'`. */ error?: string; diff --git a/app/src/utils/tauriCommands/config.ts b/app/src/utils/tauriCommands/config.ts index 1ca01321d8a..7aec7ebbce8 100644 --- a/app/src/utils/tauriCommands/config.ts +++ b/app/src/utils/tauriCommands/config.ts @@ -513,12 +513,18 @@ export async function openhumanGetAutonomySettings(): Promise> { @@ -527,9 +533,14 @@ export async function openhumanGetAgentPaths(): Promise Result { - if source_path.trim().is_empty() { - return Err("source_path must not be empty".to_string()); +/// Resolve an artifact id to the file the core's artifact store vouches for, +/// in the given workspace. Isolated from config loading for unit testing. +async fn resolve_source( + workspace_dir: &Path, + roots: &openhuman_core::agent::artifacts::FileRoots, + artifact_id: &str, +) -> Result { + let artifact_id = artifact_id.trim(); + if artifact_id.is_empty() { + return Err("artifact_id must not be empty".to_string()); } - let source = PathBuf::from(source_path); - if !source.is_absolute() { - return Err(format!( - "source_path must be absolute (came from ai_get_artifact): {source_path:?}" - )); - } - if !source.is_file() { - return Err(format!( - "artifact source not present on disk: {source_path}" - )); - } - let root = crate::file_logging::resolve_data_dir(); - assert_artifact_source(&source, &root)?; - Ok(source) -} - -/// Confirm `source` resolves inside `root` (the OpenHuman data dir) and -/// carries an `artifacts` path component — i.e. it is a workspace -/// artifact, not an arbitrary local file. Canonicalizes both sides so -/// symlink trickery can't escape the root. Isolated for unit testing -/// without touching the real home directory. -fn assert_artifact_source(source: &Path, root: &Path) -> Result<(), String> { - let canon_source = source - .canonicalize() - .map_err(|e| format!("cannot resolve source path: {e}"))?; - let canon_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); - if !canon_source.starts_with(&canon_root) { - return Err("source must be inside the OpenHuman data directory".to_string()); - } - if !canon_source - .components() - .any(|c| c.as_os_str() == "artifacts") - { - return Err("source must be a workspace artifact file".to_string()); - } - Ok(()) + openhuman_core::agent::artifacts::resolve_ready_file(workspace_dir, roots, artifact_id).await } /// Copy `source` to `dest`, returning the byte count. Isolated so it is @@ -88,10 +56,15 @@ const MAX_COLLISION_SUFFIX: u32 = 1000; #[tauri::command] pub async fn download_artifact_to_downloads( - source_path: String, + artifact_id: String, filename: String, ) -> Result { - let source = validate_source(&source_path)?; + if artifact_id.trim().is_empty() { + return Err("artifact_id must not be empty".to_string()); + } + let config = openhuman_core::config::rpc::load_config_with_timeout().await?; + let roots = openhuman_core::agent::artifacts::FileRoots::from_config(&config); + let source = resolve_source(&config.workspace_dir, &roots, &artifact_id).await?; if filename.trim().is_empty() { return Err("filename must not be empty".to_string()); } diff --git a/crates/openhuman-app/src/artifact_commands_tests.rs b/crates/openhuman-app/src/artifact_commands_tests.rs index f32279986d0..0da3a9aec26 100644 --- a/crates/openhuman-app/src/artifact_commands_tests.rs +++ b/crates/openhuman-app/src/artifact_commands_tests.rs @@ -1,4 +1,5 @@ use super::*; +use openhuman_core::agent::artifacts::FileRoots; #[test] fn sanitize_rejects_path_separators() { @@ -20,45 +21,122 @@ fn sanitize_accepts_plain_names() { assert_eq!(sanitize_filename(" trim me ").unwrap(), "trim me"); } -#[test] -fn validate_source_rejects_relative_and_empty() { - assert!(validate_source("").is_err()); - assert!(validate_source("relative/path.pptx").is_err()); - assert!(validate_source("/definitely/not/here.pptx").is_err()); +async fn ready_artifact(workspace: &Path, files_dir: &Path) -> String { + use openhuman_core::agent::artifacts::{create_artifact, finalize_artifact, ArtifactKind}; + let (meta, path) = create_artifact( + workspace, + files_dir, + ArtifactKind::Presentation, + "Deck", + "pptx", + ) + .await + .unwrap(); + std::fs::write(&path, b"deck").unwrap(); + finalize_artifact(workspace, &meta.id, 4).await.unwrap(); + meta.id } -#[test] -fn assert_artifact_source_accepts_file_under_artifacts_root() { +#[tokio::test] +async fn resolve_source_returns_the_file_in_the_files_folder() { let temp = tempfile::tempdir().unwrap(); - let root = temp.path(); - let art = root.join("users/u1/workspace/artifacts/a-1"); - std::fs::create_dir_all(&art).unwrap(); - let file = art.join("deck.pptx"); - std::fs::write(&file, b"x").unwrap(); - assert!(assert_artifact_source(&file, root).is_ok()); + let files_dir = temp.path().join("Files"); + let id = ready_artifact(temp.path(), &files_dir).await; + assert_eq!( + resolve_source(temp.path(), &FileRoots::new(&files_dir), &id) + .await + .unwrap(), + files_dir.join("deck.pptx") + ); } -#[test] -fn assert_artifact_source_rejects_file_without_artifacts_component() { +#[tokio::test] +async fn resolve_source_rejects_unknown_ids_and_paths() { + let temp = tempfile::tempdir().unwrap(); + assert!( + resolve_source(temp.path(), &FileRoots::new(temp.path()), "") + .await + .is_err() + ); + assert!(resolve_source( + temp.path(), + &FileRoots::new(temp.path()), + "no-such-artifact" + ) + .await + .is_err()); + // A path is not an id: the store's id validation refuses separators. + assert!( + resolve_source(temp.path(), &FileRoots::new(temp.path()), "/etc/passwd") + .await + .is_err() + ); +} + +#[tokio::test] +async fn resolve_source_refuses_a_file_the_store_does_not_vouch_for() { + use openhuman_core::agent::artifacts::{ArtifactKind, ArtifactMeta, ArtifactStatus}; let temp = tempfile::tempdir().unwrap(); - let root = temp.path(); - let other = root.join("users/u1/secrets"); - std::fs::create_dir_all(&other).unwrap(); - let file = other.join("token.txt"); - std::fs::write(&file, b"x").unwrap(); - assert!(assert_artifact_source(&file, root).is_err()); + let secret = temp.path().join("secret.txt"); + std::fs::write(&secret, b"private").unwrap(); + let meta = ArtifactMeta { + id: "tampered".to_string(), + kind: ArtifactKind::Other, + title: "x".to_string(), + path: "secret.txt".to_string(), + file: Some(secret.to_string_lossy().into_owned()), + file_root: Some(temp.path().join("Files").to_string_lossy().into_owned()), + size_bytes: 7, + status: ArtifactStatus::Ready, + created_at: chrono::Utc::now(), + error: None, + thread_id: None, + tool_call_id: None, + }; + let dir = temp.path().join("artifacts").join("tampered"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("meta.json"), serde_json::to_vec(&meta).unwrap()).unwrap(); + assert!(resolve_source( + temp.path(), + &FileRoots::new(temp.path().join("Files")), + "tampered" + ) + .await + .is_err()); } -#[test] -fn assert_artifact_source_rejects_file_outside_root() { - let root_dir = tempfile::tempdir().unwrap(); - let outside_dir = tempfile::tempdir().unwrap(); - // Even with an `artifacts` segment, a path outside the root is denied. - let art = outside_dir.path().join("artifacts"); - std::fs::create_dir_all(&art).unwrap(); - let file = art.join("evil.pptx"); - std::fs::write(&file, b"x").unwrap(); - assert!(assert_artifact_source(&file, root_dir.path()).is_err()); +/// Download-by-id does not take a record's `file_root` on its own say-so: a +/// record claiming a home-directory root for a private file inside it is +/// refused because that root is not one of the vouched-for files folders. +#[tokio::test] +async fn resolve_source_refuses_a_record_that_claims_its_own_root() { + use openhuman_core::agent::artifacts::{ArtifactKind, ArtifactMeta, ArtifactStatus}; + let temp = tempfile::tempdir().unwrap(); + let home = temp.path().join("home"); + std::fs::create_dir_all(&home).unwrap(); + let private = home.join("private.pdf"); + std::fs::write(&private, b"private").unwrap(); + let meta = ArtifactMeta { + id: "claims-home".to_string(), + kind: ArtifactKind::Other, + title: "x".to_string(), + path: "private.pdf".to_string(), + file: Some(private.to_string_lossy().into_owned()), + file_root: Some(home.to_string_lossy().into_owned()), + size_bytes: 7, + status: ArtifactStatus::Ready, + created_at: chrono::Utc::now(), + error: None, + thread_id: None, + tool_call_id: None, + }; + let dir = temp.path().join("artifacts").join("claims-home"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("meta.json"), serde_json::to_vec(&meta).unwrap()).unwrap(); + let files = FileRoots::new(temp.path().join("Files")); + assert!(resolve_source(temp.path(), &files, "claims-home") + .await + .is_err()); } #[tokio::test] @@ -82,7 +160,7 @@ async fn download_rejects_bad_source() { .is_err() ); assert!( - download_artifact_to_downloads("relative".to_string(), "x.pptx".to_string()) + download_artifact_to_downloads(" ".to_string(), "x.pptx".to_string()) .await .is_err() ); diff --git a/crates/openhuman-core/src/agent/agent_turn_loop_tests.rs b/crates/openhuman-core/src/agent/agent_turn_loop_tests.rs index 43e9924b998..94753f4b50a 100644 --- a/crates/openhuman-core/src/agent/agent_turn_loop_tests.rs +++ b/crates/openhuman-core/src/agent/agent_turn_loop_tests.rs @@ -195,53 +195,29 @@ async fn turn_handles_unknown_tool_gracefully() { // ═══════════════════════════════════════════════════════════════════════════ #[tokio::test] -async fn turn_recovers_from_tool_failure() { - let provider = Arc::new(ScriptedProvider::new(vec![ - tool_response(vec![NativeToolCall { - id: "tc1".into(), - name: "fail".into(), - arguments: "{}".into(), - extra_content: None, - }]), - text_response("Tool failed but I recovered"), - ])); - - let (mut agent, _tmp) = build_agent_with( - provider, - vec![Box::new(FailingTool)], - Box::new(NativeDialect), - ); - - let response = agent.turn("try failing tool").await.unwrap(); - assert!( - !response.is_empty(), - "Expected non-empty response after tool failure recovery" - ); -} - -#[tokio::test] -async fn turn_recovers_from_tool_error() { - let provider = Arc::new(ScriptedProvider::new(vec![ - tool_response(vec![NativeToolCall { - id: "tc1".into(), - name: "panicker".into(), - arguments: "{}".into(), - extra_content: None, - }]), - text_response("I recovered from the error"), - ])); - - let (mut agent, _tmp) = build_agent_with( - provider, - vec![Box::new(PanickingTool)], - Box::new(NativeDialect), - ); - - let response = agent.turn("try panicking").await.unwrap(); - assert!( - !response.is_empty(), - "Expected non-empty response after tool error recovery" - ); +async fn turn_recovers_from_tool_failure_and_tool_error() { + let cases: [(&str, Box); 2] = [ + ("fail", Box::new(FailingTool)), + ("panicker", Box::new(PanickingTool)), + ]; + for (tool_name, tool) in cases { + let provider = Arc::new(ScriptedProvider::new(vec![ + tool_response(vec![NativeToolCall { + id: "tc1".into(), + name: tool_name.into(), + arguments: "{}".into(), + extra_content: None, + }]), + text_response("I recovered"), + ])); + let (mut agent, _tmp) = build_agent_with(provider, vec![tool], Box::new(NativeDialect)); + + let response = agent.turn("try the tool").await.unwrap(); + assert!( + !response.is_empty(), + "Expected non-empty response after {tool_name} recovery" + ); + } } // ═══════════════════════════════════════════════════════════════════════════ @@ -422,68 +398,37 @@ async fn xml_dispatcher_does_not_send_tool_specs() { // ═══════════════════════════════════════════════════════════════════════════ #[tokio::test] -async fn turn_errors_on_empty_text_response() { +async fn turn_errors_on_empty_or_null_text_response() { // A completion with no text *and* no tool calls is never a valid final - // answer. The old behaviour returned `Ok("")`, which rendered as a blank - // reply and silently wedged the thread; now it surfaces as a visible - // error the user can retry on (bug-report-2026-05-26 A1). The harness - // retries an empty completion once (43660e6ef), so both attempts are - // scripted empty — a single one leaves the retry to the provider's - // default "done" reply and tests the retry instead of the error. - let empty = || ChatResponse { - text: Some(String::new()), - tool_calls: vec![], - usage: None, - reasoning_content: None, - }; - let provider = Arc::new(ScriptedProvider::new(vec![empty(), empty()])); - let script = Arc::clone(&provider); - - let (mut agent, _tmp) = build_agent_with(provider, vec![], Box::new(NativeDialect)); - - let reply = agent - .turn("hi") - .await - .expect_err("an empty provider response must error"); - // Both attempts were made: the original and the one retry. - assert_eq!( - script.calls.load(std::sync::atomic::Ordering::SeqCst), - 2, - "the empty completion must be retried exactly once before erroring" - ); - assert!( - reply.to_string().contains("empty response"), - "expected a deterministic empty-response close, got: {reply}" - ); -} - -#[tokio::test] -async fn turn_errors_on_none_text_response() { - // Both attempts: the harness retries an empty completion once. - let none = || ChatResponse { - text: None, - tool_calls: vec![], - usage: None, - reasoning_content: None, - }; - let provider = Arc::new(ScriptedProvider::new(vec![none(), none()])); - let script = Arc::clone(&provider); - - let (mut agent, _tmp) = build_agent_with(provider, vec![], Box::new(NativeDialect)); - - let reply = agent - .turn("hi") - .await - .expect_err("a null-text provider response must error"); - assert_eq!( - script.calls.load(std::sync::atomic::Ordering::SeqCst), - 2, - "the empty completion must be retried exactly once before erroring" - ); - assert!( - reply.to_string().contains("empty response"), - "expected a deterministic empty-response close, got: {reply}" - ); + // answer: it must surface as a visible error the user can retry on rather + // than a blank reply (bug-report-2026-05-26 A1). The harness retries an + // empty completion once, so both attempts are scripted empty. + for text in [Some(String::new()), None] { + let empty = || ChatResponse { + text: text.clone(), + tool_calls: vec![], + usage: None, + reasoning_content: None, + }; + let provider = Arc::new(ScriptedProvider::new(vec![empty(), empty()])); + let script = Arc::clone(&provider); + + let (mut agent, _tmp) = build_agent_with(provider, vec![], Box::new(NativeDialect)); + + let reply = agent + .turn("hi") + .await + .expect_err("an empty provider response must error"); + assert_eq!( + script.calls.load(std::sync::atomic::Ordering::SeqCst), + 2, + "the empty completion must be retried exactly once before erroring ({text:?})" + ); + assert!( + reply.to_string().contains("empty response"), + "expected a deterministic empty-response close ({text:?}), got: {reply}" + ); + } } // ═══════════════════════════════════════════════════════════════════════════ diff --git a/crates/openhuman-core/src/agent/artifacts/README.md b/crates/openhuman-core/src/agent/artifacts/README.md index a95079e8922..c9f24cad2a3 100644 --- a/crates/openhuman-core/src/agent/artifacts/README.md +++ b/crates/openhuman-core/src/agent/artifacts/README.md @@ -1,9 +1,12 @@ # artifacts Metadata store and lifecycle for agent-generated files (presentations, -documents, images) under `/artifacts/`. Producer tools -(`tools/impl/presentation`, `tools/impl/document`) call this module to -reserve an artifact directory, write their bytes, and flip the record to +documents, images, video). Metadata lives in the hidden, per-account +`/artifacts/`; the files themselves are written to a visible +files folder, `~/OpenHuman/projects/Files` by default +(`config::default_files_dir`, #5505). Producer tools +(`tools/impl/presentation`, `tools/impl/document`, `media::generation`) call +this module to reserve an artifact and its file, write their bytes, and flip the record to `Ready` or `Failed`; the module publishes the matching bus events, persists `meta.json` / `args.json`, and exposes `ai.*` RPC controllers plus three agent tools for listing, fetching, deleting, and regenerating. It never @@ -15,6 +18,8 @@ renders artifact content itself. | --- | --- | | `mod.rs` | `mod` decls and re-exports: `ArtifactKind` / `ArtifactMeta` / `ArtifactStatus`, the producer API (`create_artifact`, `finalize_artifact`, `fail_artifact`, `read_artifact_bytes`), and `all_artifacts_controller_schemas` / `all_artifacts_registered_controllers`. | | `types.rs` | `ArtifactKind` (presentation/document/image/other), `ArtifactStatus` (pending/ready/failed), `ArtifactMeta`. Enums serialize lowercase; `parse` is case-insensitive and never errors (unknown kind → `Other`, unknown status → `Pending`). `ArtifactMeta.error` and `.thread_id` are optional, `skip_serializing_if` none. | +| `files.rs` | Where the bytes live: `reserve_file` (claims `.`, then ` (2).`, with `create_new` in the shared files folder), `resolve_file` + the escape guard, `resolve_ready_file` (`pub`: the one id → existing-file lookup for readers and the desktop Download command), `remove_empty_placeholder`, the "file missing" error. | +| `migrate.rs` | `migrate_legacy_artifacts`: the idempotent, crash-safe boot move of pre-#5505 files into the files folder (copy to `..partial` → claim a name and rename → atomic meta write → delete legacy bytes). Run per account from `config::ensure_agent_dirs`. | | `store.rs` | All filesystem I/O over `tokio::fs`: `artifacts_root`, `create_artifact`, `finalize_artifact`, `fail_artifact`, `read_artifact_bytes` (`pub`); `save_artifact_meta`, `save_artifact_args`, `read_artifact_args`, `list_artifacts`, `get_artifact`, `delete_artifact` (`pub(crate)`); `validate_artifact_id` / `assert_within_root` sandboxing; the `REGENERATE_TARGET_ID` task-local; `sanitize_filename_stem`. | | `ops.rs` | RPC business logic returning `Outcome`: `ai_list_artifacts`, `ai_get_artifact`, `ai_delete_artifact`, `ai_regenerate`. `DEFAULT_LIMIT = 50`, `MAX_LIMIT = 200`. The regenerate path that re-runs `PresentationTool` is `#[cfg(feature = "documents")]`; without the feature `ai_regenerate` returns an error. | | `schemas.rs` | `ControllerSchema`s and `handle_*` fns for the four `ai.*` controllers; param helpers `read_required`, `read_optional_u64`, `read_optional_string` (whitespace-only → absent), `type_name`. | @@ -85,25 +90,43 @@ event. ## Persistence -- Root `/artifacts/`, created on demand by `artifacts_root`. -- `//meta.json`: pretty-printed `ArtifactMeta`. +- Metadata root `/artifacts/`, created on demand by + `artifacts_root`. Per account. Not in `WORKSPACE_INTERNAL_DIRS`: the + agent reads its large tool outputs back from `artifacts/tool-results/`, + so a record's `file` is bounded by the escape guard instead. +- `//meta.json`: pretty-printed `ArtifactMeta`, written + atomically (temp + rename). - `//args.json`: verbatim producer-tool args, written by the producer via `save_artifact_args`, read by `ai_regenerate`. Absent for artifacts created before it existed, which makes them non-regenerable. -- `//.`: the artifact bytes; `meta.path` is the - `/` relative path. +- `/.`: the artifact bytes. `meta.file` is the + absolute path, `meta.file_root` the files folder it was placed in, and + `meta.path` the file name. The files folder is shared by every account on + the OS user; `create_new` keeps names from colliding, and each account + lists only its own metadata. Changing the folder affects new artifacts + only; existing ones keep resolving through their recorded `file`. +- Legacy records (`file` absent) keep `meta.path` = `/` under + the metadata root until `migrate_legacy_artifacts` moves them. +- A failed generation removes its zero-byte placeholder; deleting an + artifact removes its file and its metadata directory; a `Ready` record + whose file was moved or deleted outside OpenHuman reads as "file missing". - `list_artifacts` scans root subdirectories, sorts by `created_at` descending, applies the `thread_id` filter before pagination, and skips entries whose `meta.json` is missing or corrupt (`warn!`, not an error). -- Regeneration reuses the existing directory and preserves the original - `created_at` so the artifact keeps its position in the sorted list. +- Regeneration reuses the existing directory and the file it owns, and + preserves the original `created_at` so the artifact keeps its position in + the sorted list. ## Used by - `tools/impl/presentation/mod.rs` and `tools/impl/document/mod.rs` (`documents` feature; in `scripts/ci/product-features.txt`, not in Cargo - defaults): the only producers. Presentation also uses - `read_artifact_bytes` for its image pipeline. + defaults), and `media/generation/artifact_tool.rs`: the producers. + Presentation also uses `read_artifact_bytes` for its image pipeline. +- `config/ops/agent.rs` (`ensure_agent_dirs`): creates the files folder and + runs the migration at boot. +- `crates/openhuman-app/src/artifact_commands.rs`: the desktop Download + command resolves an artifact id through `resolve_ready_file`. - `web_chat/event_bus.rs`: bridges the three events to web-channel `artifact_*` events. - `core/all.rs`: controller registry. @@ -113,8 +136,11 @@ event. - Path-traversal hardening is layered: `validate_artifact_id` rejects empty, `.`, `..`, anything containing `/` or `\`, absolute paths, and `X:` drive-letter prefixes; `assert_within_root` re-checks every resolved - path; `ai_get_artifact` and `read_artifact_bytes` additionally re-check - that a stored `meta.path` does not escape the root. + path; every reader resolves through `files::resolve_file`, which refuses + a legacy `meta.path` with `..` components (a lexical `starts_with` alone + let `/../x` through) and holds a recorded `file` to the escape guard: + absolute, no `..`, strictly inside its `file_root` (symlinks resolved), and + never `SecurityPolicy::is_always_forbidden`. - `create_artifact` rejects empty titles/extensions and extensions containing `/`, `\`, or `.`. Filename stems are lowercased ASCII `[a-z0-9_-]`, capped at 80 chars, fallback `artifact`. diff --git a/crates/openhuman-core/src/agent/artifacts/files.rs b/crates/openhuman-core/src/agent/artifacts/files.rs new file mode 100644 index 00000000000..4d4038204a9 --- /dev/null +++ b/crates/openhuman-core/src/agent/artifacts/files.rs @@ -0,0 +1,307 @@ +//! Where an artifact's bytes live (#5505). +//! +//! An artifact's metadata stays in the hidden, per-account +//! `/artifacts//`, but the file itself is written to a +//! visible folder the user can open (`~/OpenHuman/projects/Files` by default, +//! [`crate::config::default_files_dir`]). Files there are named for people — +//! `.`, then ` (2).` on collision — +//! and each record carries the absolute `file` it owns plus the `file_root` it +//! was placed in. +//! +//! The folder is shared by every account on the OS user, so a name is claimed +//! with `create_new` (an atomic "fail if it exists"): two accounts, or two +//! concurrent generations, can never be handed the same path. +//! +//! # The escape guard +//! +//! `meta.json` is data, so a record's `file` is checked before anything reads +//! or copies it. Its `file_root` counts only when it is one of the folders the +//! core vouches for ([`FileRoots`], built by the caller or from config — never +//! taken from the record), and the file must be absolute, free of `..`, +//! strictly inside that root (after resolving symlinks when it exists), and never a +//! path [`SecurityPolicy::is_always_forbidden`] rejects. That last check is the +//! same floor the agent's own file tools keep when the autonomy policy is off, +//! so a hand-edited record cannot reach further than the agent already could. +//! (`artifacts/` is deliberately not a workspace-internal dir: the agent reads +//! its own large tool outputs back from `artifacts/tool-results/`.) + +use std::path::{Component, Path, PathBuf}; + +use super::store::{artifacts_root, get_artifact}; +use super::types::{ArtifactMeta, ArtifactStatus}; +use crate::security::SecurityPolicy; + +/// The files folders the core vouches for: where new files go, plus every +/// folder an existing record may legitimately point into. A record's +/// `file_root` is honoured only when it matches one of these, so a +/// hand-edited `meta.json` cannot widen what Download and +/// `read_artifact_bytes` will serve. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FileRoots { + current: PathBuf, + trusted: Vec, +} + +impl FileRoots { + /// New files go to `current`, which is also the only trusted folder. + pub fn new(current: impl Into) -> Self { + let current = current.into(); + Self { + trusted: vec![current.clone()], + current, + } + } + + /// Also trust `folders` for existing records. + pub fn with_trusted(mut self, folders: impl IntoIterator) -> Self { + for folder in folders { + if !self.trusted.contains(&folder) { + self.trusted.push(folder); + } + } + self + } + + /// The folders for this host config: new files go to the configured + /// folder, and records made in the default folder or any folder used + /// before (`files_dir_history`) keep resolving. + pub fn from_config(config: &crate::config::Config) -> Self { + Self::new(config.files_dir()).with_trusted( + std::iter::once(crate::config::default_files_dir()) + .chain(config.files_dir_history.iter().cloned()), + ) + } + + /// Where new files are written. + pub fn current(&self) -> &Path { + &self.current + } + + /// Whether `root` is one of the vouched-for folders, compared canonically + /// where the paths exist. + fn trusts(&self, root: &Path) -> bool { + let canon = |p: &Path| p.canonicalize().unwrap_or_else(|_| p.to_path_buf()); + let root = canon(root); + self.trusted.iter().any(|t| canon(t) == root) + } +} + +impl From for FileRoots { + fn from(current: PathBuf) -> Self { + Self::new(current) + } +} + +impl From<&PathBuf> for FileRoots { + fn from(current: &PathBuf) -> Self { + Self::new(current.clone()) + } +} + +impl From<&Path> for FileRoots { + fn from(current: &Path) -> Self { + Self::new(current.to_path_buf()) + } +} + +impl From<&FileRoots> for FileRoots { + fn from(roots: &FileRoots) -> Self { + roots.clone() + } +} + +/// Collision suffixes tried before falling back to an id-tagged name. +const MAX_COLLISION_SUFFIX: u32 = 1000; + +/// Claim a fresh, human-named file in `files_dir` for `.`. +/// +/// Creates `files_dir` when missing, then creates an empty placeholder with +/// `create_new` so the name belongs to this caller before any bytes are +/// generated. Returns the placeholder's absolute path. +pub(crate) async fn reserve_file( + files_dir: &Path, + stem: &str, + ext: &str, + id: &str, +) -> Result { + tokio::fs::create_dir_all(files_dir) + .await + .map_err(|e| format!("[artifacts] failed to create files folder {files_dir:?}: {e}"))?; + let candidates = (1..=MAX_COLLISION_SUFFIX) + .map(|n| { + if n == 1 { + format!("{stem}.{ext}") + } else { + format!("{stem} ({n}).{ext}") + } + }) + .chain(std::iter::once(format!("{stem}-{id}.{ext}"))); + for name in candidates { + let candidate = files_dir.join(&name); + match tokio::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&candidate) + .await + { + Ok(_) => { + log::debug!("[artifacts] reserve_file: id={id} claimed {name:?}"); + return Ok(candidate); + } + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => { + return Err(format!( + "[artifacts] failed to reserve {candidate:?} for id={id}: {e}" + )) + } + } + } + Err(format!( + "[artifacts] no free file name for id={id} in {files_dir:?}" + )) +} + +/// Resolve the absolute path of a record's bytes, applying the escape guard. +/// +/// A record with `file` set resolves to it; a legacy record resolves to +/// `/artifacts/`. Does not require the file to exist. +pub(crate) async fn resolve_file( + workspace_dir: &Path, + meta: &ArtifactMeta, + roots: &FileRoots, +) -> Result { + let Some(file) = meta.file.as_deref() else { + let root = artifacts_root(workspace_dir).await?; + let resolved = root.join(&meta.path); + if has_parent_component(Path::new(&meta.path)) || !resolved.starts_with(&root) { + return Err(format!( + "[artifacts] meta.path {:?} escapes artifacts root for id={}", + meta.path, meta.id + )); + } + return Ok(resolved); + }; + let file = PathBuf::from(file); + let root = meta + .file_root + .as_deref() + .map(PathBuf::from) + .ok_or_else(|| format!("[artifacts] id={} has a file but no file_root", meta.id))?; + if !roots.trusts(&root) { + return Err(format!( + "[artifacts] file for id={} rejected by the escape guard: its folder is not a files folder", + meta.id + )); + } + check_within(&root, &file).map_err(|reason| { + format!( + "[artifacts] file for id={} rejected by the escape guard: {reason}", + meta.id + ) + })?; + Ok(file) +} + +fn has_parent_component(path: &Path) -> bool { + path.components().any(|c| matches!(c, Component::ParentDir)) +} + +/// The escape guard for a recorded `file` against its `file_root`. +fn check_within(root: &Path, file: &Path) -> Result<(), &'static str> { + if !root.is_absolute() || !file.is_absolute() { + return Err("path is not absolute"); + } + if has_parent_component(root) || has_parent_component(file) { + return Err("path contains '..'"); + } + if file == root || !file.starts_with(root) { + return Err("file is outside its files folder"); + } + if SecurityPolicy::is_always_forbidden(file) { + return Err("file is in a protected location"); + } + // A symlink inside the folder must not lead out of it. Fail closed: when + // anything is at the path, both sides must resolve, so a dangling or + // looping symlink (or an unresolvable folder) is refused rather than + // skipped — a skipped check would let a later read follow whatever the + // link comes to point at. Only a path with nothing at it passes here; the + // caller reports that as "file missing". + match file.symlink_metadata() { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => return Err("file could not be resolved"), + Ok(_) => { + let (Ok(canon_file), Ok(canon_root)) = (file.canonicalize(), root.canonicalize()) + else { + return Err("file could not be resolved"); + }; + if !canon_file.starts_with(&canon_root) + || SecurityPolicy::is_always_forbidden(&canon_file) + { + return Err("file resolves outside its files folder"); + } + } + } + Ok(()) +} + +/// Resolve a `Ready` artifact's bytes to an existing file. +/// +/// The one sanctioned id → path lookup for anything that reads or exports the +/// file (`read_artifact_bytes`, `ai.get_artifact`, the desktop Download +/// command). Errors when the record is not `Ready`, fails the escape guard, or +/// its file was moved or deleted outside OpenHuman. +pub async fn resolve_ready_file( + workspace_dir: &Path, + roots: &FileRoots, + artifact_id: &str, +) -> Result { + let meta = get_artifact(workspace_dir, artifact_id).await?; + if !matches!(meta.status, ArtifactStatus::Ready) { + return Err(format!( + "[artifacts] artifact id={artifact_id} is not ready (status={:?})", + meta.status + )); + } + let path = resolve_file(workspace_dir, &meta, roots).await?; + if !tokio::fs::try_exists(&path).await.unwrap_or(false) { + return Err(missing_file_error(artifact_id, &path)); + } + Ok(path) +} + +/// The error for a `Ready` record whose file is gone. +pub(crate) fn missing_file_error(artifact_id: &str, path: &Path) -> String { + format!( + "[artifacts] file missing for id={artifact_id}: {} was moved or deleted outside OpenHuman", + path.display() + ) +} + +/// A failed generation must not leave an empty file in the user's files +/// folder: drop the zero-byte placeholder `create_artifact` reserved. A file +/// with bytes (e.g. the previous output of a failed regenerate) is kept. +pub(crate) async fn remove_empty_placeholder( + workspace_dir: &Path, + meta: &ArtifactMeta, + roots: &FileRoots, +) { + if meta.file.is_none() { + return; + } + let Ok(path) = resolve_file(workspace_dir, meta, roots).await else { + return; + }; + if matches!(tokio::fs::metadata(&path).await, Ok(m) if m.is_file() && m.len() == 0) { + match tokio::fs::remove_file(&path).await { + Ok(()) => log::debug!("[artifacts] removed empty placeholder for id={}", meta.id), + Err(e) => log::warn!( + "[artifacts] could not remove empty placeholder for id={}: {e}", + meta.id + ), + } + } +} + +#[cfg(test)] +#[path = "files_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/agent/artifacts/files_tests.rs b/crates/openhuman-core/src/agent/artifacts/files_tests.rs new file mode 100644 index 00000000000..7827f0a35d5 --- /dev/null +++ b/crates/openhuman-core/src/agent/artifacts/files_tests.rs @@ -0,0 +1,427 @@ +use std::path::{Path, PathBuf}; + +use tempfile::TempDir; + +use super::*; +use crate::agent::artifacts::store::{ + create_artifact, delete_artifact, fail_artifact, finalize_artifact, list_artifacts, + read_artifact_bytes, save_artifact_meta, REGENERATE_TARGET_ID, +}; +use crate::agent::artifacts::types::ArtifactKind; + +async fn create_ready( + workspace: &Path, + files_dir: &Path, + title: &str, + bytes: &[u8], +) -> ArtifactMeta { + let (meta, path) = create_artifact(workspace, files_dir, ArtifactKind::Document, title, "txt") + .await + .expect("create_artifact"); + tokio::fs::write(&path, bytes).await.unwrap(); + finalize_artifact(workspace, &meta.id, bytes.len() as u64) + .await + .expect("finalize_artifact") +} + +fn legacy_meta(id: &str, path: &str) -> ArtifactMeta { + ArtifactMeta { + id: id.to_string(), + kind: ArtifactKind::Document, + title: "Legacy".to_string(), + path: path.to_string(), + file: None, + file_root: None, + size_bytes: 3, + status: ArtifactStatus::Ready, + created_at: chrono::Utc::now(), + error: None, + thread_id: None, + tool_call_id: None, + } +} + +fn names_in(dir: &Path) -> Vec { + let mut names: Vec = std::fs::read_dir(dir) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + names +} + +#[tokio::test] +async fn new_artifact_is_written_to_the_files_folder_not_the_workspace() { + let tmp = TempDir::new().unwrap(); + let workspace = tmp.path().join("ws"); + let files_dir = tmp.path().join("Files"); + + let (meta, path) = create_artifact( + &workspace, + &files_dir, + ArtifactKind::Presentation, + "Q3 Deck", + "pptx", + ) + .await + .unwrap(); + + assert_eq!(path, files_dir.join("q3-deck.pptx")); + assert!(path.is_file(), "the name is claimed with a placeholder"); + assert_eq!(meta.path, "q3-deck.pptx"); + assert_eq!(meta.file.as_deref(), Some(path.to_string_lossy().as_ref())); + assert_eq!( + meta.file_root.as_deref(), + Some(files_dir.to_string_lossy().as_ref()) + ); + // Metadata stays hidden in the workspace; no bytes land beside it. + assert_eq!( + names_in(&workspace.join("artifacts").join(&meta.id)), + vec!["meta.json"] + ); +} + +#[tokio::test] +async fn files_folder_is_created_on_first_use() { + let tmp = TempDir::new().unwrap(); + let files_dir = tmp.path().join("not").join("yet").join("Files"); + create_artifact( + tmp.path(), + &files_dir, + ArtifactKind::Document, + "Notes", + "docx", + ) + .await + .unwrap(); + assert!(files_dir.is_dir()); +} + +#[tokio::test] +async fn a_repeated_title_gets_a_numbered_name_instead_of_overwriting() { + let tmp = TempDir::new().unwrap(); + let files_dir = tmp.path().join("Files"); + let first = create_ready(tmp.path(), &files_dir, "Report", b"one").await; + let second = create_ready(tmp.path(), &files_dir, "Report", b"two").await; + + assert_eq!(first.path, "report.txt"); + assert_eq!(second.path, "report (2).txt"); + assert_eq!( + read_artifact_bytes(tmp.path(), &files_dir, &first.id) + .await + .unwrap(), + b"one" + ); + assert_eq!( + read_artifact_bytes(tmp.path(), &files_dir, &second.id) + .await + .unwrap(), + b"two" + ); +} + +/// The files folder is shared by every account on the OS user; metadata is +/// not. Two accounts saving the same title must get distinct files, and each +/// account's listing must show only its own records. +#[tokio::test] +async fn two_accounts_share_the_files_folder_without_clobbering_or_leaking() { + let tmp = TempDir::new().unwrap(); + let files_dir = tmp.path().join("Files"); + let ws_a = tmp.path().join("users").join("a").join("workspace"); + let ws_b = tmp.path().join("users").join("b").join("workspace"); + + let a = create_ready(&ws_a, &files_dir, "Budget", b"account a").await; + let b = create_ready(&ws_b, &files_dir, "Budget", b"account b").await; + + assert_ne!(a.file, b.file); + assert_eq!( + read_artifact_bytes(&ws_a, &files_dir, &a.id).await.unwrap(), + b"account a" + ); + assert_eq!( + read_artifact_bytes(&ws_b, &files_dir, &b.id).await.unwrap(), + b"account b" + ); + + let (listed_b, total_b) = list_artifacts(&ws_b, 0, 50, None).await.unwrap(); + assert_eq!(total_b, 1); + assert_eq!(listed_b[0].id, b.id); + assert!( + get_artifact(&ws_b, &a.id).await.is_err(), + "B cannot open A's record" + ); +} + +#[tokio::test] +async fn regenerate_overwrites_the_file_it_owns() { + let tmp = TempDir::new().unwrap(); + let files_dir = tmp.path().join("Files"); + let original = create_ready(tmp.path(), &files_dir, "Deck", b"v1").await; + + let (again, path) = REGENERATE_TARGET_ID + .scope(original.id.clone(), async { + create_artifact( + tmp.path(), + &files_dir, + ArtifactKind::Document, + "Deck", + "txt", + ) + .await + }) + .await + .unwrap(); + + assert_eq!(again.id, original.id); + assert_eq!(again.file, original.file); + assert_eq!(path, PathBuf::from(original.file.clone().unwrap())); + assert_eq!(names_in(&files_dir), vec!["deck.txt"]); +} + +#[tokio::test] +async fn a_failed_generation_leaves_no_empty_file_behind() { + let tmp = TempDir::new().unwrap(); + let files_dir = tmp.path().join("Files"); + let (meta, path) = create_artifact( + tmp.path(), + &files_dir, + ArtifactKind::Document, + "Doomed", + "docx", + ) + .await + .unwrap(); + assert!(path.is_file()); + + fail_artifact(tmp.path(), &files_dir, &meta.id, "engine exploded") + .await + .unwrap(); + + assert!(!path.exists(), "the zero-byte placeholder is removed"); +} + +#[tokio::test] +async fn delete_removes_the_file_and_the_record() { + let tmp = TempDir::new().unwrap(); + let files_dir = tmp.path().join("Files"); + let meta = create_ready(tmp.path(), &files_dir, "Gone", b"bye").await; + let file = PathBuf::from(meta.file.clone().unwrap()); + + delete_artifact(tmp.path(), &files_dir, &meta.id) + .await + .unwrap(); + + assert!(!file.exists()); + assert!(!tmp.path().join("artifacts").join(&meta.id).exists()); +} + +#[tokio::test] +async fn a_file_removed_outside_openhuman_is_reported_missing() { + let tmp = TempDir::new().unwrap(); + let files_dir = tmp.path().join("Files"); + let meta = create_ready(tmp.path(), &files_dir, "Moved", b"abc").await; + std::fs::remove_file(meta.file.as_deref().unwrap()).unwrap(); + + let err = read_artifact_bytes(tmp.path(), &files_dir, &meta.id) + .await + .unwrap_err(); + assert!(err.contains("file missing"), "{err}"); + let err = resolve_ready_file(tmp.path(), &FileRoots::new(&files_dir), &meta.id) + .await + .unwrap_err(); + assert!(err.contains("file missing"), "{err}"); +} + +async fn tampered(workspace: &Path, file: &Path, file_root: &Path) -> String { + let mut meta = legacy_meta("tampered", "x.txt"); + meta.file = Some(file.to_string_lossy().into_owned()); + meta.file_root = Some(file_root.to_string_lossy().into_owned()); + save_artifact_meta(workspace, &meta).await.unwrap(); + // Trust the record's own root here so these cases exercise the checks + // *within* a root; `a_record_pointing_outside_the_files_folders_is_refused` + // covers a root the core does not vouch for. + read_artifact_bytes(workspace, file_root, "tampered") + .await + .unwrap_err() +} + +#[tokio::test] +async fn the_escape_guard_rejects_a_file_outside_its_folder() { + let tmp = TempDir::new().unwrap(); + let files_dir = tmp.path().join("Files"); + std::fs::create_dir_all(&files_dir).unwrap(); + let secret = tmp.path().join("secret.txt"); + std::fs::write(&secret, b"private").unwrap(); + + let err = tampered(tmp.path(), &secret, &files_dir).await; + assert!(err.contains("escape guard"), "{err}"); + + let dotdot = files_dir.join("..").join("secret.txt"); + let err = tampered(tmp.path(), &dotdot, &files_dir).await; + assert!(err.contains("escape guard"), "{err}"); +} + +#[tokio::test] +async fn the_escape_guard_keeps_the_credential_store_floor() { + let tmp = TempDir::new().unwrap(); + let ssh = tmp.path().join(".ssh"); + std::fs::create_dir_all(&ssh).unwrap(); + let key = ssh.join("id_ed25519"); + std::fs::write(&key, b"-----BEGIN").unwrap(); + + // Even a record whose root claims the key's parent is refused. + let err = tampered(tmp.path(), &key, tmp.path()).await; + assert!(err.contains("escape guard"), "{err}"); +} + +#[cfg(unix)] +#[tokio::test] +async fn the_escape_guard_rejects_a_symlink_out_of_the_folder() { + let tmp = TempDir::new().unwrap(); + let files_dir = tmp.path().join("Files"); + std::fs::create_dir_all(&files_dir).unwrap(); + let secret = tmp.path().join("secret.txt"); + std::fs::write(&secret, b"private").unwrap(); + let link = files_dir.join("innocent.txt"); + std::os::unix::fs::symlink(&secret, &link).unwrap(); + + let err = tampered(tmp.path(), &link, &files_dir).await; + assert!(err.contains("escape guard"), "{err}"); +} + +#[tokio::test] +async fn a_legacy_record_still_resolves_under_the_workspace() { + let tmp = TempDir::new().unwrap(); + let meta = legacy_meta("legacy-1", "legacy-1/old.txt"); + save_artifact_meta(tmp.path(), &meta).await.unwrap(); + std::fs::write(tmp.path().join("artifacts/legacy-1/old.txt"), b"old").unwrap(); + + assert_eq!( + read_artifact_bytes(tmp.path(), tmp.path(), "legacy-1") + .await + .unwrap(), + b"old" + ); +} + +/// `root.join("../x").starts_with(root)` is true lexically, so the legacy +/// guard must reject `..` components rather than rely on `starts_with`. +#[tokio::test] +async fn a_legacy_path_with_parent_components_is_rejected() { + let tmp = TempDir::new().unwrap(); + let workspace = tmp.path().join("ws"); + std::fs::write(tmp.path().join("secret.txt"), b"private").unwrap(); + let meta = legacy_meta("legacy-2", "../../secret.txt"); + save_artifact_meta(&workspace, &meta).await.unwrap(); + + let err = read_artifact_bytes(&workspace, tmp.path(), "legacy-2") + .await + .unwrap_err(); + assert!(err.contains("escapes artifacts root"), "{err}"); +} + +/// A dangling symlink must be refused by the guard, not skipped: if its target +/// appears later, an unchecked read would follow it out of the folder. +#[cfg(unix)] +#[tokio::test] +async fn the_escape_guard_rejects_a_dangling_symlink() { + let tmp = TempDir::new().unwrap(); + let files_dir = tmp.path().join("Files"); + std::fs::create_dir_all(&files_dir).unwrap(); + let link = files_dir.join("dangling.txt"); + std::os::unix::fs::symlink(tmp.path().join("not-yet-there.txt"), &link).unwrap(); + + let err = tampered(tmp.path(), &link, &files_dir).await; + assert!(err.contains("could not be resolved"), "{err}"); +} + +#[cfg(unix)] +#[tokio::test] +async fn the_escape_guard_rejects_a_symlink_loop() { + let tmp = TempDir::new().unwrap(); + let files_dir = tmp.path().join("Files"); + std::fs::create_dir_all(&files_dir).unwrap(); + let a = files_dir.join("a.txt"); + let b = files_dir.join("b.txt"); + std::os::unix::fs::symlink(&b, &a).unwrap(); + std::os::unix::fs::symlink(&a, &b).unwrap(); + + let err = tampered(tmp.path(), &a, &files_dir).await; + assert!(err.contains("could not be resolved"), "{err}"); +} + +/// A files folder that cannot be resolved (here, itself a symlink loop) must +/// not let the check through either. +#[cfg(unix)] +#[tokio::test] +async fn the_escape_guard_rejects_an_unresolvable_folder() { + let tmp = TempDir::new().unwrap(); + let files_dir = tmp.path().join("Files"); + let other = tmp.path().join("Other"); + std::os::unix::fs::symlink(&other, &files_dir).unwrap(); + std::os::unix::fs::symlink(&files_dir, &other).unwrap(); + + let err = tampered(tmp.path(), &files_dir.join("doc.txt"), &files_dir).await; + assert!(err.contains("could not be resolved"), "{err}"); +} + +/// A path with nothing at it passes the guard and is reported as missing. +#[tokio::test] +async fn a_recorded_file_that_does_not_exist_reads_as_missing() { + let tmp = TempDir::new().unwrap(); + let files_dir = tmp.path().join("Files"); + std::fs::create_dir_all(&files_dir).unwrap(); + + let err = tampered(tmp.path(), &files_dir.join("gone.txt"), &files_dir).await; + assert!(err.contains("file missing"), "{err}"); +} + +/// The record's `file_root` is not trusted on its own say-so: a record that +/// claims a home-directory root and points at a private file inside it passes +/// every within-root check, and is still refused because that root is not one +/// of the folders the core vouches for. +#[tokio::test] +async fn a_record_pointing_outside_the_files_folders_is_refused() { + let tmp = TempDir::new().unwrap(); + let files_dir = tmp.path().join("Files"); + std::fs::create_dir_all(&files_dir).unwrap(); + let home = tmp.path().join("home"); + let private = home.join("Documents").join("private.pdf"); + std::fs::create_dir_all(private.parent().unwrap()).unwrap(); + std::fs::write(&private, b"private").unwrap(); + + let mut meta = legacy_meta("claims-home", "private.pdf"); + meta.file = Some(private.to_string_lossy().into_owned()); + meta.file_root = Some(home.to_string_lossy().into_owned()); + save_artifact_meta(tmp.path(), &meta).await.unwrap(); + + let err = read_artifact_bytes(tmp.path(), &files_dir, "claims-home") + .await + .unwrap_err(); + assert!(err.contains("not a files folder"), "{err}"); + let err = resolve_ready_file(tmp.path(), &FileRoots::new(&files_dir), "claims-home") + .await + .unwrap_err(); + assert!(err.contains("not a files folder"), "{err}"); +} + +/// A folder the user moved away from stays trusted for the records made there. +#[tokio::test] +async fn a_previously_trusted_folder_still_resolves() { + let tmp = TempDir::new().unwrap(); + let old = tmp.path().join("Old"); + let meta = create_ready(tmp.path(), &old, "Kept", b"kept").await; + + let roots = FileRoots::new(tmp.path().join("New")).with_trusted([old.clone()]); + assert_eq!( + read_artifact_bytes(tmp.path(), &roots, &meta.id) + .await + .unwrap(), + b"kept" + ); + // Without the old folder in the trusted set, the same record is refused. + let err = read_artifact_bytes(tmp.path(), tmp.path().join("New"), &meta.id) + .await + .unwrap_err(); + assert!(err.contains("not a files folder"), "{err}"); +} diff --git a/crates/openhuman-core/src/agent/artifacts/migrate.rs b/crates/openhuman-core/src/agent/artifacts/migrate.rs new file mode 100644 index 00000000000..8aeb6051261 --- /dev/null +++ b/crates/openhuman-core/src/agent/artifacts/migrate.rs @@ -0,0 +1,252 @@ +//! Move legacy artifact files into the visible files folder (#5505). +//! +//! Artifacts created before the files folder existed keep their bytes under +//! the hidden `/artifacts//`. At boot each account's legacy +//! `Ready` records are moved to the files folder so the user can find them. +//! Metadata (`meta.json`, `args.json`) never moves. +//! +//! Each file goes through four steps, ordered so that at every point the +//! record still resolves to a complete file and nothing is lost: +//! +//! 1. copy the bytes to a hidden `..partial` in the files folder and +//! flush them to disk (a copy, not a rename: the two folders can sit on +//! different volumes); +//! 2. claim a human-readable name (`create_new`, suffixed on collision) and +//! rename the partial onto it; +//! 3. rewrite `meta.json` atomically to point at the new file; +//! 4. only then delete the legacy bytes. +//! +//! A crash before step 3 leaves the record on its legacy path, and the next +//! boot migrates again; the worst leftover is one duplicate visible copy +//! (after step 2) or a `.partial` (after step 1), which the next run removes. +//! A crash after step 3 leaves a legacy copy the next run deletes. Running it +//! again on a migrated workspace changes nothing. + +use std::path::{Path, PathBuf}; + +use super::files; +use super::store::{artifacts_root, save_artifact_meta}; +use super::types::{ArtifactMeta, ArtifactStatus}; + +/// What one migration pass did, for the boot log and tests. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct MigrationReport { + /// Records whose file was moved into the files folder. + pub moved: usize, + /// Legacy copies removed for records already pointing at the files folder. + pub cleaned: usize, + /// Records left on their legacy path because a step failed. + pub failed: usize, +} + +/// A step to stop after, simulating a crash. Test-only in effect: the public +/// entry point always passes `None`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum CrashAfter { + Copy, + Rename, + MetaWrite, +} + +const PARTIAL_SUFFIX: &str = ".partial"; +/// Files in `/artifacts//` that are metadata, never bytes. +const METADATA_FILES: &[&str] = &["meta.json", "args.json", "meta.json.tmp"]; + +/// Migrate every legacy `Ready` artifact in `workspace_dir` into `files_dir`. +/// Idempotent and safe to run on every boot. +pub async fn migrate_legacy_artifacts(workspace_dir: &Path, files_dir: &Path) -> MigrationReport { + migrate_with(workspace_dir, files_dir, None).await +} + +pub(crate) async fn migrate_with( + workspace_dir: &Path, + files_dir: &Path, + crash_after: Option, +) -> MigrationReport { + let mut report = MigrationReport::default(); + let Ok(root) = artifacts_root(workspace_dir).await else { + return report; + }; + let Ok(mut entries) = tokio::fs::read_dir(&root).await else { + return report; + }; + let mut records = Vec::new(); + while let Ok(Some(entry)) = entries.next_entry().await { + let meta_path = entry.path().join("meta.json"); + let Ok(raw) = tokio::fs::read_to_string(&meta_path).await else { + continue; + }; + let Ok(meta) = serde_json::from_str::(&raw) else { + continue; + }; + records.push((entry.path(), meta)); + } + if records.is_empty() { + return report; + } + remove_stale_partials(files_dir).await; + + for (artifact_dir, meta) in records { + if meta.file.is_some() { + // Already migrated; a crash after step 3 may have left the legacy + // copy behind. + report.cleaned += remove_legacy_leftovers(&artifact_dir).await; + continue; + } + if !matches!(meta.status, ArtifactStatus::Ready) { + continue; + } + let Some(src) = legacy_bytes(&root, &artifact_dir, &meta) else { + continue; + }; + match migrate_one(workspace_dir, files_dir, &meta, &src, crash_after).await { + Ok(true) => report.moved += 1, + Ok(false) => {} + Err(e) => { + report.failed += 1; + log::warn!( + "[artifacts][migrate] id={} left on legacy path: {e}", + meta.id + ); + } + } + if crash_after.is_some() { + break; + } + } + log::info!( + "[artifacts][migrate] moved={} cleaned={} failed={}", + report.moved, + report.cleaned, + report.failed + ); + report +} + +/// The legacy on-disk bytes of an unmigrated record, when present and inside +/// its own artifact directory. +fn legacy_bytes(root: &Path, artifact_dir: &Path, meta: &ArtifactMeta) -> Option { + let rel = Path::new(&meta.path); + if rel.is_absolute() + || rel + .components() + .any(|c| matches!(c, std::path::Component::ParentDir)) + { + return None; + } + let candidate = root.join(rel); + (candidate.starts_with(artifact_dir) && candidate.is_file()).then_some(candidate) +} + +/// For a migrated record, every regular file in its artifact directory other +/// than the metadata sidecars is a legacy copy left by a crash between steps 3 +/// and 4. Returns how many were removed. +async fn remove_legacy_leftovers(artifact_dir: &Path) -> usize { + let Ok(mut entries) = tokio::fs::read_dir(artifact_dir).await else { + return 0; + }; + let mut removed = 0; + while let Ok(Some(entry)) = entries.next_entry().await { + let name = entry.file_name().to_string_lossy().into_owned(); + if METADATA_FILES.contains(&name.as_str()) { + continue; + } + if matches!(entry.file_type().await, Ok(ft) if ft.is_file()) + && tokio::fs::remove_file(entry.path()).await.is_ok() + { + removed += 1; + } + } + removed +} + +/// Returns `Ok(true)` when the file was moved, `Ok(false)` on a simulated crash. +async fn migrate_one( + workspace_dir: &Path, + files_dir: &Path, + meta: &ArtifactMeta, + src: &Path, + crash_after: Option, +) -> Result { + tokio::fs::create_dir_all(files_dir) + .await + .map_err(|e| format!("create files folder: {e}"))?; + + // Step 1: copy to a hidden partial and flush it. + let partial = files_dir.join(format!(".{}{PARTIAL_SUFFIX}", meta.id)); + let _ = tokio::fs::remove_file(&partial).await; + tokio::fs::copy(src, &partial) + .await + .map_err(|e| format!("copy: {e}"))?; + tokio::fs::File::open(&partial) + .await + .map_err(|e| format!("reopen partial: {e}"))? + .sync_all() + .await + .map_err(|e| format!("flush partial: {e}"))?; + if crash_after == Some(CrashAfter::Copy) { + return Ok(false); + } + + // Step 2: claim a readable name and move the partial onto it. + let file_name = src + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let (stem, ext) = match file_name.rsplit_once('.') { + Some((stem, ext)) if !stem.is_empty() => (stem.to_string(), ext.to_string()), + _ => (file_name.clone(), "bin".to_string()), + }; + let target = files::reserve_file(files_dir, &stem, &ext, &meta.id).await?; + if let Err(e) = tokio::fs::rename(&partial, &target).await { + let _ = tokio::fs::remove_file(&target).await; + let _ = tokio::fs::remove_file(&partial).await; + return Err(format!("rename partial: {e}")); + } + if crash_after == Some(CrashAfter::Rename) { + return Ok(false); + } + + // Step 3: point the record at the moved file. + let mut moved = meta.clone(); + moved.path = target + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + moved.file = Some(target.to_string_lossy().into_owned()); + moved.file_root = Some(files_dir.to_string_lossy().into_owned()); + if let Err(e) = save_artifact_meta(workspace_dir, &moved).await { + let _ = tokio::fs::remove_file(&target).await; + return Err(format!("write meta: {e}")); + } + if crash_after == Some(CrashAfter::MetaWrite) { + return Ok(false); + } + + // Step 4: the record no longer points at the legacy bytes. + if let Err(e) = tokio::fs::remove_file(src).await { + log::warn!( + "[artifacts][migrate] id={} moved; legacy copy not removed: {e}", + meta.id + ); + } + log::debug!("[artifacts][migrate] id={} moved to files folder", meta.id); + Ok(true) +} + +/// Remove `..partial` leftovers from an interrupted earlier run. +async fn remove_stale_partials(files_dir: &Path) { + let Ok(mut entries) = tokio::fs::read_dir(files_dir).await else { + return; + }; + while let Ok(Some(entry)) = entries.next_entry().await { + let name = entry.file_name().to_string_lossy().into_owned(); + if name.starts_with('.') && name.ends_with(PARTIAL_SUFFIX) { + let _ = tokio::fs::remove_file(entry.path()).await; + } + } +} + +#[cfg(test)] +#[path = "migrate_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/agent/artifacts/migrate_tests.rs b/crates/openhuman-core/src/agent/artifacts/migrate_tests.rs new file mode 100644 index 00000000000..22a89adda3f --- /dev/null +++ b/crates/openhuman-core/src/agent/artifacts/migrate_tests.rs @@ -0,0 +1,324 @@ +use std::path::{Path, PathBuf}; + +use tempfile::TempDir; + +use super::*; +use crate::agent::artifacts::store::{ + get_artifact, list_artifacts, read_artifact_bytes, save_artifact_args, save_artifact_meta, +}; +use crate::agent::artifacts::types::ArtifactKind; + +/// A pre-#5505 record: bytes under `/artifacts//`. +async fn legacy(workspace: &Path, id: &str, name: &str, bytes: &[u8], status: ArtifactStatus) { + let meta = ArtifactMeta { + id: id.to_string(), + kind: ArtifactKind::Document, + title: name.to_string(), + path: format!("{id}/{name}"), + file: None, + file_root: None, + size_bytes: bytes.len() as u64, + status, + created_at: chrono::Utc::now(), + error: None, + thread_id: None, + tool_call_id: None, + }; + save_artifact_meta(workspace, &meta).await.unwrap(); + save_artifact_args(workspace, id, &serde_json::json!({ "title": name })) + .await + .unwrap(); + std::fs::write(workspace.join("artifacts").join(id).join(name), bytes).unwrap(); +} + +fn legacy_path(workspace: &Path, id: &str, name: &str) -> PathBuf { + workspace.join("artifacts").join(id).join(name) +} + +/// Visible files in the folder (hidden `.partial`s excluded). +fn visible(files_dir: &Path) -> Vec { + let Ok(entries) = std::fs::read_dir(files_dir) else { + return Vec::new(); + }; + let mut names: Vec = entries + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .filter(|n| !n.starts_with('.')) + .collect(); + names.sort(); + names +} + +fn partials(files_dir: &Path) -> usize { + std::fs::read_dir(files_dir) + .map(|entries| { + entries + .filter(|e| { + e.as_ref() + .unwrap() + .file_name() + .to_string_lossy() + .ends_with(".partial") + }) + .count() + }) + .unwrap_or(0) +} + +#[tokio::test] +async fn moves_a_legacy_file_into_the_files_folder() { + let tmp = TempDir::new().unwrap(); + let ws = tmp.path().join("ws"); + let files_dir = tmp.path().join("Files"); + legacy( + &ws, + "a1", + "q3-deck.pptx", + b"deck bytes", + ArtifactStatus::Ready, + ) + .await; + + let report = migrate_legacy_artifacts(&ws, &files_dir).await; + + assert_eq!( + report, + MigrationReport { + moved: 1, + cleaned: 0, + failed: 0 + } + ); + let meta = get_artifact(&ws, "a1").await.unwrap(); + assert_eq!( + meta.file.as_deref(), + Some(files_dir.join("q3-deck.pptx").to_string_lossy().as_ref()) + ); + assert_eq!( + meta.file_root.as_deref(), + Some(files_dir.to_string_lossy().as_ref()) + ); + assert_eq!(meta.path, "q3-deck.pptx"); + assert_eq!( + read_artifact_bytes(&ws, &files_dir, "a1").await.unwrap(), + b"deck bytes" + ); + assert!( + !legacy_path(&ws, "a1", "q3-deck.pptx").exists(), + "legacy bytes removed" + ); + assert!( + ws.join("artifacts/a1/args.json").is_file(), + "metadata never moves" + ); +} + +#[tokio::test] +async fn running_twice_changes_nothing() { + let tmp = TempDir::new().unwrap(); + let ws = tmp.path().join("ws"); + let files_dir = tmp.path().join("Files"); + legacy(&ws, "a1", "notes.docx", b"notes", ArtifactStatus::Ready).await; + + migrate_legacy_artifacts(&ws, &files_dir).await; + let second = migrate_legacy_artifacts(&ws, &files_dir).await; + + assert_eq!(second, MigrationReport::default()); + assert_eq!(visible(&files_dir), vec!["notes.docx"]); + assert_eq!( + read_artifact_bytes(&ws, &files_dir, "a1").await.unwrap(), + b"notes" + ); +} + +#[tokio::test] +async fn leaves_pending_and_failed_records_alone() { + let tmp = TempDir::new().unwrap(); + let ws = tmp.path().join("ws"); + let files_dir = tmp.path().join("Files"); + legacy(&ws, "p1", "half.pptx", b"", ArtifactStatus::Pending).await; + legacy(&ws, "f1", "broken.pptx", b"", ArtifactStatus::Failed).await; + + let report = migrate_legacy_artifacts(&ws, &files_dir).await; + + assert_eq!(report, MigrationReport::default()); + assert!(get_artifact(&ws, "p1").await.unwrap().file.is_none()); + assert!(get_artifact(&ws, "f1").await.unwrap().file.is_none()); + assert!(visible(&files_dir).is_empty()); +} + +#[tokio::test] +async fn a_name_already_in_the_folder_is_never_overwritten() { + let tmp = TempDir::new().unwrap(); + let ws = tmp.path().join("ws"); + let files_dir = tmp.path().join("Files"); + std::fs::create_dir_all(&files_dir).unwrap(); + std::fs::write(files_dir.join("report.txt"), b"the user's own file").unwrap(); + legacy( + &ws, + "a1", + "report.txt", + b"agent report", + ArtifactStatus::Ready, + ) + .await; + + migrate_legacy_artifacts(&ws, &files_dir).await; + + assert_eq!( + std::fs::read(files_dir.join("report.txt")).unwrap(), + b"the user's own file" + ); + assert_eq!( + get_artifact(&ws, "a1").await.unwrap().path, + "report (2).txt" + ); + assert_eq!( + read_artifact_bytes(&ws, &files_dir, "a1").await.unwrap(), + b"agent report" + ); +} + +/// Two accounts migrate a same-named file into the one shared folder: both +/// survive under distinct names, and each account still lists only its own. +#[tokio::test] +async fn two_accounts_migrate_into_the_shared_folder_without_clobbering() { + let tmp = TempDir::new().unwrap(); + let files_dir = tmp.path().join("Files"); + let ws_a = tmp.path().join("users/a/workspace"); + let ws_b = tmp.path().join("users/b/workspace"); + legacy( + &ws_a, + "a1", + "budget.xlsx", + b"a's budget", + ArtifactStatus::Ready, + ) + .await; + legacy( + &ws_b, + "b1", + "budget.xlsx", + b"b's budget", + ArtifactStatus::Ready, + ) + .await; + + migrate_legacy_artifacts(&ws_a, &files_dir).await; + migrate_legacy_artifacts(&ws_b, &files_dir).await; + + assert_eq!(visible(&files_dir), vec!["budget (2).xlsx", "budget.xlsx"]); + assert_eq!( + read_artifact_bytes(&ws_a, &files_dir, "a1").await.unwrap(), + b"a's budget" + ); + assert_eq!( + read_artifact_bytes(&ws_b, &files_dir, "b1").await.unwrap(), + b"b's budget" + ); + let (listed, total) = list_artifacts(&ws_b, 0, 50, None).await.unwrap(); + assert_eq!((total, listed[0].id.as_str()), (1, "b1")); +} + +// ── Crash safety: stop after each step, check nothing is lost, rerun ────── + +#[tokio::test] +async fn a_crash_after_the_copy_leaves_the_record_intact_and_is_redone() { + let tmp = TempDir::new().unwrap(); + let ws = tmp.path().join("ws"); + let files_dir = tmp.path().join("Files"); + legacy(&ws, "a1", "deck.pptx", b"deck", ArtifactStatus::Ready).await; + + migrate_with(&ws, &files_dir, Some(CrashAfter::Copy)).await; + assert!(get_artifact(&ws, "a1").await.unwrap().file.is_none()); + assert_eq!( + read_artifact_bytes(&ws, &files_dir, "a1").await.unwrap(), + b"deck" + ); + assert_eq!(partials(&files_dir), 1); + + let report = migrate_legacy_artifacts(&ws, &files_dir).await; + assert_eq!(report.moved, 1); + assert_eq!(partials(&files_dir), 0, "the stale partial is removed"); + assert_eq!(visible(&files_dir), vec!["deck.pptx"]); + assert_eq!( + read_artifact_bytes(&ws, &files_dir, "a1").await.unwrap(), + b"deck" + ); +} + +#[tokio::test] +async fn a_crash_after_the_rename_loses_nothing_and_leaves_at_most_one_duplicate() { + let tmp = TempDir::new().unwrap(); + let ws = tmp.path().join("ws"); + let files_dir = tmp.path().join("Files"); + legacy(&ws, "a1", "deck.pptx", b"deck", ArtifactStatus::Ready).await; + + migrate_with(&ws, &files_dir, Some(CrashAfter::Rename)).await; + assert!(get_artifact(&ws, "a1").await.unwrap().file.is_none()); + assert_eq!( + read_artifact_bytes(&ws, &files_dir, "a1").await.unwrap(), + b"deck" + ); + + migrate_legacy_artifacts(&ws, &files_dir).await; + let meta = get_artifact(&ws, "a1").await.unwrap(); + assert!(meta.file.is_some()); + assert_eq!( + read_artifact_bytes(&ws, &files_dir, "a1").await.unwrap(), + b"deck" + ); + assert!(visible(&files_dir).len() <= 2); + assert!(!legacy_path(&ws, "a1", "deck.pptx").exists()); +} + +#[tokio::test] +async fn a_crash_after_the_meta_write_is_finished_by_the_next_run() { + let tmp = TempDir::new().unwrap(); + let ws = tmp.path().join("ws"); + let files_dir = tmp.path().join("Files"); + legacy(&ws, "a1", "deck.pptx", b"deck", ArtifactStatus::Ready).await; + + migrate_with(&ws, &files_dir, Some(CrashAfter::MetaWrite)).await; + assert!(get_artifact(&ws, "a1").await.unwrap().file.is_some()); + assert!( + legacy_path(&ws, "a1", "deck.pptx").exists(), + "legacy copy not yet removed" + ); + assert_eq!( + read_artifact_bytes(&ws, &files_dir, "a1").await.unwrap(), + b"deck" + ); + + let report = migrate_legacy_artifacts(&ws, &files_dir).await; + assert_eq!( + report, + MigrationReport { + moved: 0, + cleaned: 1, + failed: 0 + } + ); + assert!(!legacy_path(&ws, "a1", "deck.pptx").exists()); + assert_eq!(visible(&files_dir), vec!["deck.pptx"]); + assert!( + ws.join("artifacts/a1/args.json").is_file(), + "sidecars are never cleaned" + ); +} + +/// A partial left by an interrupted run whose record has since gone (deleted +/// between runs) is not overwritten by any later copy; the sweep removes it. +#[tokio::test] +async fn an_orphaned_partial_from_an_earlier_run_is_removed() { + let tmp = TempDir::new().unwrap(); + let ws = tmp.path().join("ws"); + let files_dir = tmp.path().join("Files"); + std::fs::create_dir_all(&files_dir).unwrap(); + std::fs::write(files_dir.join(".deleted-record.partial"), b"half a deck").unwrap(); + legacy(&ws, "a1", "notes.docx", b"notes", ArtifactStatus::Ready).await; + + migrate_legacy_artifacts(&ws, &files_dir).await; + + assert_eq!(partials(&files_dir), 0); + assert_eq!(visible(&files_dir), vec!["notes.docx"]); +} diff --git a/crates/openhuman-core/src/agent/artifacts/mod.rs b/crates/openhuman-core/src/agent/artifacts/mod.rs index c0679861e25..9bd595dc02c 100644 --- a/crates/openhuman-core/src/agent/artifacts/mod.rs +++ b/crates/openhuman-core/src/agent/artifacts/mod.rs @@ -1,9 +1,13 @@ +pub mod files; +pub mod migrate; pub mod ops; pub mod schemas; pub mod store; pub mod tools; pub mod types; +pub use files::{resolve_ready_file, FileRoots}; +pub use migrate::{migrate_legacy_artifacts, MigrationReport}; pub use schemas::{ all_controller_schemas as all_artifacts_controller_schemas, all_registered_controllers as all_artifacts_registered_controllers, diff --git a/crates/openhuman-core/src/agent/artifacts/ops.rs b/crates/openhuman-core/src/agent/artifacts/ops.rs index ccf4aa046b8..eb0cca8b579 100644 --- a/crates/openhuman-core/src/agent/artifacts/ops.rs +++ b/crates/openhuman-core/src/agent/artifacts/ops.rs @@ -79,15 +79,16 @@ pub async fn ai_get_artifact(config: &Config, artifact_id: &str) -> Result, + previous: Option, + files_dir: std::path::PathBuf, +} + +impl DefaultFilesDir { + fn under(tmp: &TempDir) -> Self { + let lock = crate::config::TEST_ENV_LOCK + .lock() + .unwrap_or_else(|e| e.into_inner()); + let previous = std::env::var_os("OPENHUMAN_PROJECTS_DIR"); + let projects = tmp.path().join("projects"); + unsafe { + std::env::set_var("OPENHUMAN_PROJECTS_DIR", &projects); + } + Self { + _lock: lock, + previous, + files_dir: crate::config::default_files_dir(), + } + } +} + +impl Drop for DefaultFilesDir { + fn drop(&mut self) { + unsafe { + match self.previous.take() { + Some(v) => std::env::set_var("OPENHUMAN_PROJECTS_DIR", v), + None => std::env::remove_var("OPENHUMAN_PROJECTS_DIR"), + } + } + } +} + +#[tokio::test] +async fn get_returns_the_files_folder_path() { + use crate::agent::artifacts::store::{create_artifact, finalize_artifact}; + use crate::agent::artifacts::types::ArtifactKind; + let tmp = TempDir::new().unwrap(); + let config = test_config(&tmp); + let default = DefaultFilesDir::under(&tmp); + let files_dir = default.files_dir.clone(); + let (meta, path) = create_artifact( + tmp.path(), + &files_dir, + ArtifactKind::Document, + "Plan", + "docx", + ) + .await + .unwrap(); + std::fs::write(&path, b"plan").unwrap(); + finalize_artifact(tmp.path(), &meta.id, 4).await.unwrap(); + + let value = ai_get_artifact(&config, &meta.id) + .await + .unwrap() + .into_cli_compatible_json() + .unwrap(); + + assert_eq!( + value["absolute_path"], + files_dir.join("plan.docx").to_string_lossy().as_ref() + ); +} + +#[tokio::test] +async fn get_reports_a_ready_file_removed_outside_openhuman() { + use crate::agent::artifacts::store::{create_artifact, finalize_artifact}; + use crate::agent::artifacts::types::ArtifactKind; + let tmp = TempDir::new().unwrap(); + let config = test_config(&tmp); + let default = DefaultFilesDir::under(&tmp); + let (meta, path) = create_artifact( + tmp.path(), + &default.files_dir, + ArtifactKind::Document, + "Plan", + "docx", + ) + .await + .unwrap(); + std::fs::write(&path, b"plan").unwrap(); + finalize_artifact(tmp.path(), &meta.id, 4).await.unwrap(); + std::fs::remove_file(&path).unwrap(); + + let err = ai_get_artifact(&config, &meta.id).await.unwrap_err(); + assert!(err.contains("file missing"), "{err}"); +} + +/// A record whose `file_root` is not a files folder the core vouches for is +/// refused by get, and delete leaves the file it names alone. +#[tokio::test] +async fn get_and_delete_refuse_a_record_rooted_outside_the_files_folder() { + use crate::agent::artifacts::store::save_artifact_meta; + use crate::agent::artifacts::types::{ArtifactKind, ArtifactMeta, ArtifactStatus}; + let tmp = TempDir::new().unwrap(); + let config = test_config(&tmp); + let _default = DefaultFilesDir::under(&tmp); + let home = tmp.path().join("home"); + let private = home.join("private.pdf"); + std::fs::create_dir_all(&home).unwrap(); + std::fs::write(&private, b"private").unwrap(); + save_artifact_meta( + tmp.path(), + &ArtifactMeta { + id: "claims-home".to_string(), + kind: ArtifactKind::Document, + title: "x".to_string(), + path: "private.pdf".to_string(), + file: Some(private.to_string_lossy().into_owned()), + file_root: Some(home.to_string_lossy().into_owned()), + size_bytes: 7, + status: ArtifactStatus::Ready, + created_at: chrono::Utc::now(), + error: None, + thread_id: None, + tool_call_id: None, + }, + ) + .await + .unwrap(); + + let err = ai_get_artifact(&config, "claims-home").await.unwrap_err(); + assert!(err.contains("not a files folder"), "{err}"); + + ai_delete_artifact(&config, "claims-home").await.unwrap(); + assert!( + private.exists(), + "the file outside the files folder is left alone" + ); +} diff --git a/crates/openhuman-core/src/agent/artifacts/schemas.rs b/crates/openhuman-core/src/agent/artifacts/schemas.rs index c3b2f57da23..c190e1232ea 100644 --- a/crates/openhuman-core/src/agent/artifacts/schemas.rs +++ b/crates/openhuman-core/src/agent/artifacts/schemas.rs @@ -120,7 +120,7 @@ pub fn schemas(function: &str) -> ControllerSchema { FieldSchema { name: "path", ty: TypeSchema::String, - comment: "Relative path from the artifacts root.", + comment: "File name relative to its root: the files folder, or the artifacts root for a legacy record.", required: true, }, FieldSchema { diff --git a/crates/openhuman-core/src/agent/artifacts/store.rs b/crates/openhuman-core/src/agent/artifacts/store.rs index e72cba68a13..124826b53f6 100644 --- a/crates/openhuman-core/src/agent/artifacts/store.rs +++ b/crates/openhuman-core/src/agent/artifacts/store.rs @@ -1,9 +1,11 @@ use std::path::{Path, PathBuf}; +use super::files::{self, FileRoots}; use super::types::{ArtifactMeta, ArtifactStatus}; const ARTIFACTS_SUBDIR: &str = "artifacts"; const META_FILENAME: &str = "meta.json"; +const META_TMP_FILENAME: &str = "meta.json.tmp"; /// Sidecar file holding the verbatim producer-tool arguments that /// generated the artifact, persisted next to `meta.json` so a failed /// card's Retry button can re-dispatch the exact same generation @@ -113,12 +115,24 @@ pub(crate) async fn save_artifact_meta( meta.id ) })?; - tokio::fs::write(&meta_path, json).await.map_err(|e| { + // Write-then-rename so a crash mid-write never leaves a truncated + // meta.json: the migration relies on the record flipping atomically + // from the legacy path to the moved file. + let tmp_path = artifact_dir.join(META_TMP_FILENAME); + tokio::fs::write(&tmp_path, json).await.map_err(|e| { format!( "[artifacts] failed to write meta.json for id={}: {e}", meta.id ) })?; + tokio::fs::rename(&tmp_path, &meta_path) + .await + .map_err(|e| { + format!( + "[artifacts] failed to commit meta.json for id={}: {e}", + meta.id + ) + })?; log::debug!("[artifacts] saved meta.json for id={}", meta.id); Ok(()) } @@ -311,27 +325,18 @@ pub(crate) async fn read_artifact_args( /// Read the raw bytes of a finalized artifact's output file. /// /// Single source of truth for resolving an artifact id → on-disk bytes: -/// callers (e.g. the presentation image pipeline) must not reconstruct -/// the `//` path scheme themselves. Validates the id, -/// confirms the resolved path stays under the artifacts root, and refuses -/// artifacts that are not yet [`ArtifactStatus::Ready`] (a `Pending` / -/// `Failed` record may have no bytes — or partial bytes — on disk). +/// callers (e.g. the presentation image pipeline) must not reconstruct the +/// path themselves. Goes through [`files::resolve_ready_file`], which refuses +/// records that are not yet [`ArtifactStatus::Ready`] (a `Pending` / `Failed` +/// record may have no bytes — or partial bytes — on disk), applies the escape +/// guard, and reports a file removed outside OpenHuman as missing. pub async fn read_artifact_bytes( workspace_dir: &Path, + roots: impl Into, artifact_id: &str, ) -> Result, String> { log::debug!("[artifacts] read_artifact_bytes: id={artifact_id}"); - let meta = get_artifact(workspace_dir, artifact_id).await?; - if !matches!(meta.status, ArtifactStatus::Ready) { - return Err(format!( - "[artifacts] artifact id={artifact_id} is not ready (status={:?})", - meta.status - )); - } - let root = artifacts_root(workspace_dir).await?; - // `meta.path` is the store-internal `/` relative path. - let file_path = root.join(&meta.path); - assert_within_root(&root, &file_path)?; + let file_path = files::resolve_ready_file(workspace_dir, &roots.into(), artifact_id).await?; let bytes = tokio::fs::read(&file_path) .await .map_err(|e| format!("[artifacts] failed to read artifact bytes id={artifact_id}: {e}"))?; @@ -342,13 +347,38 @@ pub async fn read_artifact_bytes( Ok(bytes) } -/// Delete an artifact directory and all its contents. -pub(crate) async fn delete_artifact(workspace_dir: &Path, artifact_id: &str) -> Result<(), String> { +/// Delete an artifact: its file in the files folder, then its metadata +/// directory. A file already gone, or one the escape guard rejects, is left +/// alone (logged) and the record is still removed. +pub(crate) async fn delete_artifact( + workspace_dir: &Path, + roots: impl Into, + artifact_id: &str, +) -> Result<(), String> { + let roots = roots.into(); log::debug!("[artifacts] delete_artifact: id={artifact_id}"); validate_artifact_id(artifact_id)?; let root = artifacts_root(workspace_dir).await?; let artifact_dir = root.join(artifact_id); assert_within_root(&root, &artifact_dir)?; + if let Ok(meta) = get_artifact(workspace_dir, artifact_id).await { + if meta.file.is_some() { + match files::resolve_file(workspace_dir, &meta, &roots).await { + Ok(file) => match tokio::fs::remove_file(&file).await { + Ok(()) => log::debug!( + "[artifacts] delete_artifact: removed file for id={artifact_id}" + ), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => { + return Err(format!( + "[artifacts] failed to delete file for id={artifact_id}: {e}" + )) + } + }, + Err(e) => log::warn!("[artifacts] delete_artifact: leaving file in place: {e}"), + } + } + } tokio::fs::remove_dir_all(&artifact_dir) .await .map_err(|e| format!("[artifacts] failed to delete artifact id={artifact_id}: {e}"))?; @@ -428,11 +458,12 @@ fn sanitize_filename_stem(title: &str) -> String { /// bridge silently drops the event for lack of a routing target. pub async fn create_artifact( workspace_dir: &Path, + files: impl Into, kind: super::types::ArtifactKind, title: &str, extension: &str, ) -> Result<(ArtifactMeta, PathBuf), String> { - create_artifact_for_call(workspace_dir, kind, title, extension, None).await + create_artifact_for_call(workspace_dir, files, kind, title, extension, None).await } /// As [`create_artifact`], but also records the provider-assigned @@ -443,11 +474,14 @@ pub async fn create_artifact( /// exactly like [`create_artifact`]. pub async fn create_artifact_for_call( workspace_dir: &Path, + files: impl Into, kind: super::types::ArtifactKind, title: &str, extension: &str, tool_call_id: Option<&str>, ) -> Result<(ArtifactMeta, PathBuf), String> { + let roots = files.into(); + let files_dir = roots.current(); let trimmed_title = title.trim(); if trimmed_title.is_empty() { return Err("[artifacts] create_artifact: title must not be empty".to_string()); @@ -474,8 +508,7 @@ pub async fn create_artifact_for_call( .filter(|target| !target.trim().is_empty()); let is_regenerate = reused_id.is_some(); let id = reused_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); - let filename = format!("{}.{trimmed_ext}", sanitize_filename_stem(trimmed_title)); - let relative_path = format!("{id}/{filename}"); + let stem = sanitize_filename_stem(trimmed_title); let root = artifacts_root(workspace_dir).await?; let artifact_dir = root.join(&id); @@ -488,7 +521,6 @@ pub async fn create_artifact_for_call( artifact_dir ) })?; - let absolute_path = artifact_dir.join(&filename); // Capture the originating chat thread (if any) at create-time so the // panel can repopulate from disk after a redux-persist purge — see @@ -501,20 +533,46 @@ pub async fn create_artifact_for_call( // `created_at` — bumping it to now would reorder the artifact to the // top of the `created_at`-sorted list/panel even though it is the same // logical artifact (#3162, CodeRabbit). New artifacts always stamp now. - let created_at = if is_regenerate { - match get_artifact(workspace_dir, &id).await { - Ok(prev) => prev.created_at, - Err(_) => chrono::Utc::now(), - } + // A regenerate also overwrites the file it already owns (#5505) rather + // than claiming a second name in the files folder. + let previous = if is_regenerate { + get_artifact(workspace_dir, &id).await.ok() } else { - chrono::Utc::now() + None + }; + let created_at = previous + .as_ref() + .map(|prev| prev.created_at) + .unwrap_or_else(chrono::Utc::now); + let owned_file = match previous.as_ref().filter(|prev| prev.file.is_some()) { + Some(prev) => match files::resolve_file(workspace_dir, prev, &roots).await { + Ok(path) if tokio::fs::try_exists(&path).await.unwrap_or(false) => prev + .file_root + .clone() + .map(|root| (path, PathBuf::from(root))), + _ => None, + }, + None => None, + }; + let (absolute_path, file_root) = match owned_file { + Some(pair) => pair, + None => ( + files::reserve_file(files_dir, &stem, trimmed_ext, &id).await?, + files_dir.to_path_buf(), + ), }; + let filename = absolute_path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| format!("{stem}.{trimmed_ext}")); let meta = ArtifactMeta { id: id.clone(), kind, title: trimmed_title.to_string(), - path: relative_path, + path: filename, + file: Some(absolute_path.to_string_lossy().into_owned()), + file_root: Some(file_root.to_string_lossy().into_owned()), size_bytes: 0, status: ArtifactStatus::Pending, created_at, @@ -607,6 +665,7 @@ pub async fn finalize_artifact( /// rules as [`finalize_artifact`]. pub async fn fail_artifact( workspace_dir: &Path, + roots: impl Into, artifact_id: &str, reason: &str, ) -> Result { @@ -614,6 +673,7 @@ pub async fn fail_artifact( meta.status = ArtifactStatus::Failed; meta.error = Some(reason.to_string()); save_artifact_meta(workspace_dir, &meta).await?; + files::remove_empty_placeholder(workspace_dir, &meta, &roots.into()).await; // Log only the size of the reason — it can carry provider stderr // / user-derived content, which we don't want flushed verbatim // into structured logs. The full payload is still persisted on diff --git a/crates/openhuman-core/src/agent/artifacts/store_tests.rs b/crates/openhuman-core/src/agent/artifacts/store_tests.rs index a96a1e95cb9..93d3ce29b26 100644 --- a/crates/openhuman-core/src/agent/artifacts/store_tests.rs +++ b/crates/openhuman-core/src/agent/artifacts/store_tests.rs @@ -10,6 +10,8 @@ fn make_meta(id: &str, title: &str, created_at: chrono::DateTime) -> Artifa kind: ArtifactKind::Document, title: title.to_string(), path: format!("{id}/file.txt"), + file: None, + file_root: None, size_bytes: 100, status: ArtifactStatus::Ready, created_at, @@ -103,7 +105,9 @@ async fn delete_removes_directory_and_meta() { // Confirm it exists get_artifact(tmp.path(), "del-id").await.unwrap(); - delete_artifact(tmp.path(), "del-id").await.unwrap(); + delete_artifact(tmp.path(), tmp.path(), "del-id") + .await + .unwrap(); // Should now be gone let err = get_artifact(tmp.path(), "del-id").await.unwrap_err(); @@ -116,7 +120,7 @@ async fn delete_removes_directory_and_meta() { #[tokio::test] async fn delete_nonexistent_returns_error() { let tmp = TempDir::new().unwrap(); - let err = delete_artifact(tmp.path(), "nonexistent-id") + let err = delete_artifact(tmp.path(), tmp.path(), "nonexistent-id") .await .unwrap_err(); assert!( @@ -261,9 +265,15 @@ async fn create_artifact_publishes_artifact_pending_event() { let _handle = collector.subscribe(); let tmp = TempDir::new().unwrap(); - let (meta, _path) = create_artifact(tmp.path(), ArtifactKind::Presentation, "Q3 Deck", "pptx") - .await - .expect("create_artifact succeeds"); + let (meta, _path) = create_artifact( + tmp.path(), + &tmp.path().join("Files"), + ArtifactKind::Presentation, + "Q3 Deck", + "pptx", + ) + .await + .expect("create_artifact succeeds"); let expected_workspace = tmp.path().to_string_lossy().into_owned(); // The bus is broadcast-based and processed off-task — wait until the @@ -352,10 +362,15 @@ async fn artifact_events_fill_request_id_from_chat_context() { let (meta, _path) = APPROVAL_CHAT_CONTEXT .scope(ctx, async { - let (meta, _path) = - create_artifact(tmp.path(), ArtifactKind::Document, "Report", "pdf") - .await - .expect("create_artifact succeeds"); + let (meta, _path) = create_artifact( + tmp.path(), + &tmp.path().join("Files"), + ArtifactKind::Document, + "Report", + "pdf", + ) + .await + .expect("create_artifact succeeds"); finalize_artifact(tmp.path(), &meta.id, 42) .await .expect("finalize_artifact succeeds"); @@ -427,11 +442,16 @@ async fn fail_artifact_fills_request_id_from_chat_context() { let meta = APPROVAL_CHAT_CONTEXT .scope(ctx, async { - let (meta, _path) = - create_artifact(tmp.path(), ArtifactKind::Document, "Report", "pdf") - .await - .expect("create_artifact succeeds"); - fail_artifact(tmp.path(), &meta.id, "boom") + let (meta, _path) = create_artifact( + tmp.path(), + &tmp.path().join("Files"), + ArtifactKind::Document, + "Report", + "pdf", + ) + .await + .expect("create_artifact succeeds"); + fail_artifact(tmp.path(), tmp.path(), &meta.id, "boom") .await .expect("fail_artifact succeeds"); meta @@ -497,9 +517,15 @@ async fn read_args_errors_when_absent() { #[tokio::test] async fn create_artifact_mints_fresh_id_without_scope() { let tmp = TempDir::new().unwrap(); - let (meta, _path) = create_artifact(tmp.path(), ArtifactKind::Presentation, "Q3 Deck", "pptx") - .await - .unwrap(); + let (meta, _path) = create_artifact( + tmp.path(), + &tmp.path().join("Files"), + ArtifactKind::Presentation, + "Q3 Deck", + "pptx", + ) + .await + .unwrap(); // A normal (non-regenerate) create mints a UUID, never an empty id. assert!(!meta.id.is_empty()); assert_eq!(meta.status, ArtifactStatus::Pending); @@ -511,7 +537,14 @@ async fn create_artifact_reuses_id_inside_regenerate_scope() { let workspace = tmp.path().to_path_buf(); let (meta, _path) = REGENERATE_TARGET_ID .scope("reused-id".to_string(), async move { - create_artifact(&workspace, ArtifactKind::Presentation, "Q3 Deck", "pptx").await + create_artifact( + &workspace, + &workspace.join("Files"), + ArtifactKind::Presentation, + "Q3 Deck", + "pptx", + ) + .await }) .await .unwrap(); @@ -528,9 +561,15 @@ async fn regenerate_preserves_original_created_at() { let workspace = tmp.path().to_path_buf(); // First create stamps `created_at = now`. - let (first, _) = create_artifact(tmp.path(), ArtifactKind::Presentation, "Deck", "pptx") - .await - .unwrap(); + let (first, _) = create_artifact( + tmp.path(), + &tmp.path().join("Files"), + ArtifactKind::Presentation, + "Deck", + "pptx", + ) + .await + .unwrap(); let original_created = first.created_at; // Regenerate reuses the id; created_at must NOT be bumped, otherwise the @@ -539,7 +578,14 @@ async fn regenerate_preserves_original_created_at() { let ws = workspace.clone(); let (second, _) = REGENERATE_TARGET_ID .scope(id.clone(), async move { - create_artifact(&ws, ArtifactKind::Presentation, "Deck", "pptx").await + create_artifact( + &ws, + &ws.join("Files"), + ArtifactKind::Presentation, + "Deck", + "pptx", + ) + .await }) .await .unwrap(); diff --git a/crates/openhuman-core/src/agent/artifacts/tools.rs b/crates/openhuman-core/src/agent/artifacts/tools.rs index 34a8bbc51e8..bbf27725cfd 100644 --- a/crates/openhuman-core/src/agent/artifacts/tools.rs +++ b/crates/openhuman-core/src/agent/artifacts/tools.rs @@ -3,12 +3,13 @@ //! Each tool is a thin shim over a read/delete handler in //! [`crate::agent::artifacts::ops`], unwrapping the `Outcome` //! envelope and emitting the inner JSON value. The artifacts domain owns -//! agent-generated files (presentations/documents/images) under -//! `/artifacts/`; these tools let the agent enumerate and -//! inspect what it has produced. +//! agent-generated files (presentations/documents/images): metadata under +//! `/artifacts/`, the files themselves in the visible files folder +//! (`~/OpenHuman/projects/Files`, #5505); these tools let the agent enumerate +//! and inspect what it has produced. //! //! `artifact_list` / `artifact_get` are read-only and default-enabled. -//! `artifact_delete` is `Dangerous` (irreversible directory removal) and +//! `artifact_delete` is `Dangerous` (irreversibly removes the file and its record) and //! ships default-OFF — it must be opted in via the tool toggle //! (the `artifact_delete` `ToolFamily` in `TOOL_FAMILIES`, //! `tools/user_filter.rs`). diff --git a/crates/openhuman-core/src/agent/artifacts/types.rs b/crates/openhuman-core/src/agent/artifacts/types.rs index 0dfa3dc4c81..b3fc107246f 100644 --- a/crates/openhuman-core/src/agent/artifacts/types.rs +++ b/crates/openhuman-core/src/agent/artifacts/types.rs @@ -80,8 +80,21 @@ pub struct ArtifactMeta { pub kind: ArtifactKind, /// Human-readable title. pub title: String, - /// Relative path from the artifacts root, e.g. `"/deck.pptx"`. + /// The file's name relative to its root. For a record with [`Self::file`] + /// set it is relative to [`Self::file_root`] (e.g. `"deck.pptx"`); for a + /// legacy record it is relative to `/artifacts/` + /// (e.g. `"/deck.pptx"`). pub path: String, + /// Absolute path of the deliverable in the visible files folder (#5505). + /// `None` for records written before that folder existed; those resolve + /// under `/artifacts/` until the boot migration moves them. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub file: Option, + /// The files folder [`Self::file`] was placed in. Recorded per artifact so + /// changing the folder later does not strand existing files, and so the + /// escape guard has a root to check `file` against. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub file_root: Option, /// Artifact file size in bytes. pub size_bytes: u64, /// Current lifecycle status. diff --git a/crates/openhuman-core/src/agent/artifacts/types_tests.rs b/crates/openhuman-core/src/agent/artifacts/types_tests.rs index 9e23f17182b..33e263170e8 100644 --- a/crates/openhuman-core/src/agent/artifacts/types_tests.rs +++ b/crates/openhuman-core/src/agent/artifacts/types_tests.rs @@ -4,11 +4,6 @@ use serde_json::json; // ── ArtifactKind ─────────────────────────────────────────────────────────── -#[test] -fn artifact_kind_default_is_other() { - assert_eq!(ArtifactKind::default(), ArtifactKind::Other); -} - #[test] fn artifact_kind_as_str_roundtrip() { assert_eq!(ArtifactKind::Presentation.as_str(), "presentation"); @@ -34,20 +29,6 @@ fn artifact_kind_parse_case_insensitive() { assert_eq!(ArtifactKind::parse(""), ArtifactKind::Other); } -#[test] -fn artifact_kind_serde_roundtrip() { - for kind in [ - ArtifactKind::Presentation, - ArtifactKind::Document, - ArtifactKind::Image, - ArtifactKind::Other, - ] { - let json = serde_json::to_value(&kind).unwrap(); - let back: ArtifactKind = serde_json::from_value(json).unwrap(); - assert_eq!(back, kind); - } -} - #[test] fn artifact_kind_serializes_lowercase() { assert_eq!( @@ -62,11 +43,6 @@ fn artifact_kind_serializes_lowercase() { // ── ArtifactStatus ───────────────────────────────────────────────────────── -#[test] -fn artifact_status_default_is_pending() { - assert_eq!(ArtifactStatus::default(), ArtifactStatus::Pending); -} - #[test] fn artifact_status_as_str_roundtrip() { assert_eq!(ArtifactStatus::Pending.as_str(), "pending"); @@ -83,46 +59,8 @@ fn artifact_status_parse_case_insensitive() { assert_eq!(ArtifactStatus::parse(""), ArtifactStatus::Pending); } -#[test] -fn artifact_status_serde_roundtrip() { - for status in [ - ArtifactStatus::Pending, - ArtifactStatus::Ready, - ArtifactStatus::Failed, - ] { - let json = serde_json::to_value(&status).unwrap(); - let back: ArtifactStatus = serde_json::from_value(json).unwrap(); - assert_eq!(back, status); - } -} - // ── ArtifactMeta ─────────────────────────────────────────────────────────── -#[test] -fn artifact_meta_serde_roundtrip() { - let meta = ArtifactMeta { - id: "abc-123".to_string(), - kind: ArtifactKind::Presentation, - title: "Q3 Deck".to_string(), - path: "abc-123/deck.pptx".to_string(), - size_bytes: 204800, - status: ArtifactStatus::Ready, - created_at: Utc.with_ymd_and_hms(2025, 6, 1, 12, 0, 0).unwrap(), - error: None, - thread_id: Some("thread-42".to_string()), - tool_call_id: None, - }; - let json = serde_json::to_value(&meta).unwrap(); - assert_eq!(json["id"], "abc-123"); - assert_eq!(json["kind"], "presentation"); - assert_eq!(json["status"], "ready"); - let back: ArtifactMeta = serde_json::from_value(json).unwrap(); - assert_eq!(back.id, meta.id); - assert_eq!(back.kind, meta.kind); - assert_eq!(back.status, meta.status); - assert_eq!(back.size_bytes, meta.size_bytes); -} - #[test] fn artifact_meta_json_shape() { let meta = ArtifactMeta { @@ -130,6 +68,8 @@ fn artifact_meta_json_shape() { kind: ArtifactKind::Other, title: "test".to_string(), path: "x/file.txt".to_string(), + file: None, + file_root: None, size_bytes: 0, status: ArtifactStatus::Pending, created_at: Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap(), @@ -187,6 +127,8 @@ fn artifact_meta_thread_id_none_is_skipped_in_serialised_form() { kind: ArtifactKind::Other, title: "t".to_string(), path: "x/t.txt".to_string(), + file: None, + file_root: None, size_bytes: 0, status: ArtifactStatus::Pending, created_at: Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap(), @@ -210,6 +152,8 @@ fn artifact_meta_thread_id_some_round_trips() { kind: ArtifactKind::Other, title: "t".to_string(), path: "x/t.txt".to_string(), + file: None, + file_root: None, size_bytes: 0, status: ArtifactStatus::Pending, created_at: Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap(), diff --git a/crates/openhuman-core/src/agent/harness/README.md b/crates/openhuman-core/src/agent/harness/README.md index 48c6bb2e199..b4b81b8a423 100644 --- a/crates/openhuman-core/src/agent/harness/README.md +++ b/crates/openhuman-core/src/agent/harness/README.md @@ -48,7 +48,6 @@ used here (not defined here) by `agent_graph.rs` and `fork_context.rs`. | `tool_result_artifacts/` | Wiring only: `new_tool_result_store` hands `tinyagents_harness::artifacts::tool_results` OpenHuman's redactor (`SanitizingRedactor`), `file_read`/`use_skill` names and `FileReadTool::MAX_FILE_SIZE_BYTES`. The store, `[tool_result_preview]` envelope, budgets and paged reads live in the crate. | | `memory_context.rs`, `memory_context_safety.rs` | Working-memory and `[Cross-chat context]` lines surfaced into the prompt (capped by `WORKING_MEMORY_LIMIT`); trust-tier wrapping of recalled entries that came from connectors (`wrap_untrusted_for_agent`). The read-index, dedupe, write, update-index enforcement state machine for memory-mutating tools (issue #4116) now lives in `tinyagents_harness::middleware` (`MemoryProtocolTracker`). | | `required_output.rs` | Pure validate/repair/synthesize primitives (issue #4117) that guarantee a required structured-output block (for example a `thoughts` JSON block) on every accepted turn. The orchestration that calls these lives on the session in `../session_host/turn/`. | -| `parse_wire_tests.rs` | Test-only fixtures for OpenHuman's own wire vocabulary (`inference::provider::ToolCall`, native-history JSON, OpenAI function-calling payloads). The actual `` parsing (tags, fenced blocks, bare JSON, `` XML, GLM grammar, p-format) moved to the vendored `tinytools_agent` crate; nothing about recovering a tool call from model text stayed here. | | `credentials.rs` | `scrub_credentials`: regex scrubbing of credential-shaped text (key/value secrets, AWS access-key IDs, `sk-...` keys). Applied to every tool result by `CredentialScrubMiddleware` in `agent/tinyagents/middleware/credential_scrub.rs`, installed as the innermost tool wrap so nothing downstream sees the raw secret. | ## Public surface @@ -112,9 +111,7 @@ turn lifecycle are in `../session_host/`; `run_subagent`, ## Tests -- Unit: `harness_tests.rs`, `harness_gap_tests.rs`, - `harness_tool_call_parsing_tests.rs`, - `harness_tool_call_parsing_edge_case_tests.rs`, plus `*_tests.rs` files +- Unit: `harness_tool_call_parsing_edge_case_tests.rs`, plus `*_tests.rs` files beside each sub-module (`tool_result_artifacts/mod_tests.rs`, `artifact_offload/artifact_offload_tests.rs`, `archivist/{lifecycle,recap,resummarise}_tests.rs`). diff --git a/crates/openhuman-core/src/agent/harness/archivist/lifecycle.rs b/crates/openhuman-core/src/agent/harness/archivist/lifecycle.rs index 376099467d4..f0f719b083f 100644 --- a/crates/openhuman-core/src/agent/harness/archivist/lifecycle.rs +++ b/crates/openhuman-core/src/agent/harness/archivist/lifecycle.rs @@ -652,6 +652,14 @@ impl ArchivistHook { } } } + // A driver that embeds only what it stores (hosted memory) has no + // embed-on-request route: that is its shape, not a failure. + Err(e @ crate::memory::api::error::MemoryError::Unsupported { .. }) => { + tracing::debug!( + "[archivist] driver does not embed on request — skipping segment embedding \ + segment={segment_id} model={model_signature}: {e}" + ); + } Err(e) => { tracing::warn!( "[archivist] embed call failed (non-fatal) segment={segment_id} model={model_signature}: {e}" diff --git a/crates/openhuman-core/src/agent/harness/archivist/recap.rs b/crates/openhuman-core/src/agent/harness/archivist/recap.rs index 2fff00b1088..5f6b245b7c5 100644 --- a/crates/openhuman-core/src/agent/harness/archivist/recap.rs +++ b/crates/openhuman-core/src/agent/harness/archivist/recap.rs @@ -349,6 +349,14 @@ impl ArchivistHook { heuristic fallback segment={segment_id} elapsed_ms={elapsed_ms}" ); } + // A driver with a tree but no model to fold with (hosted + // memory) says so: the heuristic recap is its answer. + Err(e @ crate::memory::api::error::MemoryError::Unsupported { .. }) => { + tracing::debug!( + "[archivist] summarize_entries: driver has no summariser — \ + heuristic fallback segment={segment_id}: {e}" + ); + } Err(e) => { tracing::warn!( "[archivist] summarize_entries: LLM recap failed (non-fatal) \ diff --git a/crates/openhuman-core/src/agent/harness/harness_gap_tests.rs b/crates/openhuman-core/src/agent/harness/harness_gap_tests.rs deleted file mode 100644 index 4f6fc61028f..00000000000 --- a/crates/openhuman-core/src/agent/harness/harness_gap_tests.rs +++ /dev/null @@ -1,90 +0,0 @@ -//! Gap-filling unit tests for the agent harness. -//! -//! These tests cover paths that were missing from the existing `*_tests.rs` -//! co-located files as identified by a coverage gap analysis: -//! -//! 1. Full user→LLM→tool→result→final turn cycle — now covered by the -//! tinyagents route's tests (`crates/openhuman-core/src/agent/tinyagents/tests.rs`), which -//! exercise `run_turn_via_tinyagents_shared` end to end. -//! 2. `MaxIterationsExceeded` downcasts to the typed `AgentError` variant. -//! 3. `visible_tool_names` whitelist: tools outside the set are treated as unknown. -//! 4. `ContextGuard` surfaces `ContextExhausted` and aborts the loop. -//! 5. `parse_tool_calls` fallback formats — covered in `tinytools-agent`'s own -//! parse tests (`parse/test/regressions.rs`). -//! 6. `DateTimeSection` produces an ISO-8601-like timestamp with a timezone token. -//! 7. `parse_tool_timeout_secs` default and boundary cases. -//! 8. Spawn-depth gate (`SpawnDepthExceeded`) is covered in -//! `../subagent_host/ops_tests.rs` because it lives at the `run_subagent` -//! boundary. -//! -//! Items that have NO underlying code and therefore cannot be tested: -//! - Follow-up resolution ("yes"/"no" disambiguation) — not implemented. -//! - Silence timer (SilenceTimeout, 600 s) — not implemented. -//! - `` XML attribute form — the parser does not parse attributes; -//! only the tag body (JSON) is used. - -use crate::tools::timeout::parse_tool_timeout_secs; - -// ───────────────────────────────────────────────────────────────────────────── -// Item 1 — Full turn cycle: user → LLM emits tool call → tool executes → -// result injected → LLM produces final text. -// ───────────────────────────────────────────────────────────────────────────── - -// NOTE: The `ContextGuard`/`ContextCheckResult` tests that used to live here -// (context_guard_exhausted_after_circuit_breaker_and_95pct_utilization, -// context_guard_update_usage_raises_window_from_response) were removed during the -// tinyagents migration: the context reducer shell (`context/guard.rs`) was -// deleted (commit d55ea9a5d) and the tested API no longer exists. - -// ───────────────────────────────────────────────────────────────────────────── -// Item 5 (tool timeout) — parse_tool_timeout_secs defaults and boundaries. -// Already covered in tool_timeout/mod.rs but pinned here for the gap report. -// ───────────────────────────────────────────────────────────────────────────── - -#[test] -fn tool_timeout_parse_default_and_boundaries() { - // Default when absent. - assert_eq!(parse_tool_timeout_secs(None), 120); - // Default when non-numeric. - assert_eq!(parse_tool_timeout_secs(Some("bad")), 120); - // Boundary values. - assert_eq!(parse_tool_timeout_secs(Some("1")), 1); - assert_eq!(parse_tool_timeout_secs(Some("3600")), 3600); - // Out of range → default. - assert_eq!(parse_tool_timeout_secs(Some("0")), 120); - assert_eq!(parse_tool_timeout_secs(Some("3601")), 120); -} - -// ───────────────────────────────────────────────────────────────────────────── -// Item 8 — Current-time grounding (#3602). The volatile timestamp now rides the -// per-turn user message via `current_datetime_line` (so a long-lived -// session's frozen prompt prefix can't go stale); `DateTimeSection` -// carries only the static grounding *rule*. Pin both halves. -// ───────────────────────────────────────────────────────────────────────────── - -#[test] -fn current_datetime_line_matches_iso8601_date_and_utc_offset_pattern() { - // The per-turn stamp is the one carrying the concrete clock — assert its - // ISO-8601 date, UTC offset, and IANA zone (or `UTC` fallback). - let payload = crate::agent::prompts::current_datetime_line(); - - // Parse the concrete `YYYY-MM-DD HH:MM:SS` prefix rather than counting - // loose digits, so a malformed layout can't slip through. - let rest = payload - .strip_prefix("Current Date & Time: ") - .expect("stamp must start with the canonical prefix"); - let dt = rest - .get(0..19) - .expect("stamp must include YYYY-MM-DD HH:MM:SS"); - chrono::NaiveDateTime::parse_from_str(dt, "%Y-%m-%d %H:%M:%S") - .expect("timestamp must match YYYY-MM-DD HH:MM:SS"); - assert!( - payload.contains("UTC"), - "stamp must contain UTC offset marker: {payload}" - ); - let has_iana = payload.contains('/') || payload.contains(" UTC "); - assert!( - has_iana, - "stamp must contain an IANA zone (slashed) or UTC fallback: {payload}" - ); -} diff --git a/crates/openhuman-core/src/agent/harness/harness_tests.rs b/crates/openhuman-core/src/agent/harness/harness_tests.rs deleted file mode 100644 index 70ff6c4f31c..00000000000 --- a/crates/openhuman-core/src/agent/harness/harness_tests.rs +++ /dev/null @@ -1,11 +0,0 @@ -use super::parse_tests::tools_to_openai_format; -use crate::tools; -use std::sync::Arc; - -fn build_tool_instructions(tools: &[Box]) -> String { - let specs = tools.iter().map(|tool| tool.spec()).collect::>(); - tinytools_agent::dialect::XmlDialect::instructions(&specs) -} - -#[path = "harness_tool_call_parsing_tests.rs"] -mod harness_tool_call_parsing_tests; diff --git a/crates/openhuman-core/src/agent/harness/harness_tool_call_parsing_tests.rs b/crates/openhuman-core/src/agent/harness/harness_tool_call_parsing_tests.rs deleted file mode 100644 index 6b918cca476..00000000000 --- a/crates/openhuman-core/src/agent/harness/harness_tool_call_parsing_tests.rs +++ /dev/null @@ -1,46 +0,0 @@ -use super::*; - -#[test] -fn build_tool_instructions_includes_all_tools() { - use crate::security::SecurityPolicy; - let security = Arc::new(SecurityPolicy::from_config( - &crate::config::AutonomyConfig::default(), - std::path::Path::new("/tmp"), - std::path::Path::new("/tmp"), - )); - let tools = tools::ops::default_tools(security); - let instructions = build_tool_instructions(&tools); - - assert!(instructions.contains("## Tool Use Protocol")); - assert!(instructions.contains("")); - assert!(instructions.contains("shell")); - assert!(instructions.contains("file_read")); - assert!(instructions.contains("file_write")); -} - -#[test] -fn tools_to_openai_format_produces_valid_schema() { - use crate::security::SecurityPolicy; - let security = Arc::new(SecurityPolicy::from_config( - &crate::config::AutonomyConfig::default(), - std::path::Path::new("/tmp"), - std::path::Path::new("/tmp"), - )); - let tools = tools::ops::default_tools(security); - let formatted = tools_to_openai_format(&tools); - - assert!(!formatted.is_empty()); - for tool_json in &formatted { - assert_eq!(tool_json["type"], "function"); - assert!(tool_json["function"]["name"].is_string()); - assert!(tool_json["function"]["description"].is_string()); - assert!(!tool_json["function"]["name"].as_str().unwrap().is_empty()); - } - // Verify known tools are present - let names: Vec<&str> = formatted - .iter() - .filter_map(|t| t["function"]["name"].as_str()) - .collect(); - assert!(names.contains(&"shell")); - assert!(names.contains(&"file_read")); -} diff --git a/crates/openhuman-core/src/agent/harness/mod.rs b/crates/openhuman-core/src/agent/harness/mod.rs index 86ae64b5c8c..742dde17287 100644 --- a/crates/openhuman-core/src/agent/harness/mod.rs +++ b/crates/openhuman-core/src/agent/harness/mod.rs @@ -52,12 +52,3 @@ pub(crate) use spawn_depth_context::{with_spawn_depth, MAX_SPAWN_DEPTH}; pub use task_recency_context::{current_task_recency_window, with_task_recency_window}; pub(crate) use graph::run_channel_turn_via_graph; - -#[cfg(test)] -mod harness_gap_tests; -#[cfg(test)] -#[path = "parse_wire_tests.rs"] -mod parse_tests; -#[cfg(test)] -#[path = "harness_tests.rs"] -mod tests; diff --git a/crates/openhuman-core/src/agent/harness/parse_tests.rs b/crates/openhuman-core/src/agent/harness/parse_tests.rs deleted file mode 100644 index f43d467d768..00000000000 --- a/crates/openhuman-core/src/agent/harness/parse_tests.rs +++ /dev/null @@ -1,128 +0,0 @@ -//! Tests for the OpenHuman-specific half of tool-call parsing. -//! -//! The parser tests moved with the parsers, to -//! `tinytools_agent`. What is exercised here is the wire -//! vocabulary that stayed: OpenHuman's `ToolCall`, its native-history JSON -//! (including the Gemini `thought_signature` round-trip), and its OpenAI -//! function-calling payload. - -use super::*; -use async_trait::async_trait; -use tinytools::ToolResult; - -struct StubTool(&'static str); - -#[async_trait] -impl Tool for StubTool { - fn name(&self) -> &str { - self.0 - } - - fn description(&self) -> &str { - "stub tool" - } - - fn parameters_schema(&self) -> serde_json::Value { - serde_json::json!({ - "type": "object", - "properties": { - "value": { "type": "string" } - } - }) - } - - async fn execute(&self, _args: serde_json::Value) -> anyhow::Result { - Ok(ToolResult::success("ok")) - } -} -#[test] -fn structured_tool_call_and_history_helpers_round_trip_expected_shapes() { - let tool_calls = vec![NativeToolCall { - id: "call-1".into(), - name: "echo".into(), - arguments: "{\"value\":\"hello\"}".into(), - extra_content: None, - }]; - - let parsed = parse_structured_tool_calls(&tool_calls); - assert_eq!(parsed.len(), 1); - assert_eq!(parsed[0].arguments, serde_json::json!({ "value": "hello" })); - - let native = build_native_assistant_history("done", None, &tool_calls); - let native_json: serde_json::Value = serde_json::from_str(&native).expect("valid json"); - assert_eq!(native_json["content"], "done"); - assert_eq!(native_json["tool_calls"][0]["id"], "call-1"); - // No reasoning supplied -> field omitted entirely (non-reasoning models - // must not gain a spurious `reasoning_content` key). - assert!(native_json.get("reasoning_content").is_none()); - - // DeepSeek thinking mode: reasoning must round-trip onto the tool-call - // turn (Sentry TAURI-RUST-4KB). - let native_reasoning = - build_native_assistant_history("done", Some(" step-by-step thoughts "), &tool_calls); - let reasoning_json: serde_json::Value = - serde_json::from_str(&native_reasoning).expect("valid json"); - assert_eq!(reasoning_json["reasoning_content"], "step-by-step thoughts"); - // Whitespace-only reasoning is treated as absent. - let native_blank = build_native_assistant_history("done", Some(" "), &tool_calls); - let blank_json: serde_json::Value = serde_json::from_str(&native_blank).expect("valid json"); - assert!(blank_json.get("reasoning_content").is_none()); - - let xml_history = build_assistant_history_with_tool_calls("", &tool_calls); - assert!(xml_history.contains("")); - assert!(xml_history.contains("\"name\":\"echo\"")); -} -#[test] -fn build_native_assistant_history_persists_per_call_extra_content() { - let tool_calls = vec![ - NativeToolCall { - id: "call-a".into(), - name: "shell".into(), - arguments: "{}".into(), - extra_content: Some(serde_json::json!({"google":{"thought_signature":"SIG_A"}})), - }, - NativeToolCall { - id: "call-b".into(), - name: "read".into(), - arguments: "{}".into(), - extra_content: Some(serde_json::json!({"google":{"thought_signature":"SIG_B"}})), - }, - // A call that never had a signature must NOT gain an empty key. - NativeToolCall { - id: "call-c".into(), - name: "noop".into(), - arguments: "{}".into(), - extra_content: None, - }, - ]; - - let native = build_native_assistant_history("on it", None, &tool_calls); - let json: serde_json::Value = serde_json::from_str(&native).expect("valid json"); - - assert_eq!( - json.pointer("/tool_calls/0/extra_content/google/thought_signature") - .and_then(|v| v.as_str()), - Some("SIG_A"), - "first parallel call's signature must be persisted" - ); - assert_eq!( - json.pointer("/tool_calls/1/extra_content/google/thought_signature") - .and_then(|v| v.as_str()), - Some("SIG_B"), - "second parallel call's signature must be persisted (not just the first)" - ); - assert!( - json.pointer("/tool_calls/2/extra_content").is_none(), - "a call without extra_content must omit the field, keeping non-Gemini history byte-identical" - ); -} -#[test] -fn tools_to_openai_format_uses_tool_metadata() { - let tools: Vec> = vec![Box::new(StubTool("echo")), Box::new(StubTool("shell"))]; - let payload = tools_to_openai_format(&tools); - - assert_eq!(payload.len(), 2); - assert_eq!(payload[0]["type"], "function"); - assert_eq!(payload[0]["function"]["name"], "echo"); - assert_eq!(payload[1]["function"]["description"], "stub tool"); -} diff --git a/crates/openhuman-core/src/agent/harness/parse_wire_tests.rs b/crates/openhuman-core/src/agent/harness/parse_wire_tests.rs deleted file mode 100644 index 39c6925745a..00000000000 --- a/crates/openhuman-core/src/agent/harness/parse_wire_tests.rs +++ /dev/null @@ -1,145 +0,0 @@ -//! Tool-call parsing — OpenHuman's adapter over -//! [`tinytools_agent`]. -//! -//! The parsers themselves moved to the crate: `` tags in their -//! several spellings, fenced blocks, bare JSON, Anthropic-style `` XML, -//! the GLM grammar, and the p-format bodies. Nothing about recovering a tool -//! call from model text is OpenHuman-specific, so none of it stayed. -//! -//! What is left below speaks OpenHuman's own wire vocabulary — its -//! `NativeToolCall`, its native-history JSON, its OpenAI -//! function-calling payload. All of it is `#[cfg(test)]`: these are the -//! fixtures its own tests assert against, and they never compiled into a -//! production build even before the move. - -#[cfg(test)] -use tinytools::Tool; -#[cfg(test)] -use tinytools_agent::dialect::NativeToolCall; -#[cfg(test)] -use tinytools_agent::{CallSource, ParsedToolCall}; - -#[cfg(test)] -pub(crate) fn parse_structured_tool_calls(tool_calls: &[NativeToolCall]) -> Vec { - tool_calls - .iter() - .map(|call| ParsedToolCall { - name: call.name.clone(), - arguments: serde_json::from_str::(&call.arguments) - .unwrap_or_else(|_| serde_json::Value::Object(serde_json::Map::new())), - id: Some(call.id.clone()), - source: CallSource::Native, - }) - .collect() -} - -/// Build assistant history entry in JSON format for native tool-call APIs. -/// `convert_messages` in the OpenRouter provider parses this JSON to reconstruct -/// the proper `NativeMessage` with structured `tool_calls`. -/// -/// `reasoning_content` carries the model's thinking output (when the provider -/// surfaced it). It is persisted so the next request can replay it: DeepSeek's -/// thinking mode rejects an `assistant` turn that carries `tool_calls` if its -/// `reasoning_content` is not passed back (Sentry TAURI-RUST-4KB). Omitted from -/// the JSON when empty, so non-reasoning models are unaffected. -#[cfg(test)] -pub(crate) fn build_native_assistant_history( - text: &str, - reasoning_content: Option<&str>, - tool_calls: &[NativeToolCall], -) -> String { - let calls_json: Vec = tool_calls - .iter() - .map(|tc| { - let mut call = serde_json::json!({ - "id": tc.id, - "name": tc.name, - "arguments": tc.arguments, - }); - // Persist Gemini's per-call `thought_signature` (TAURI-RUST-4PK / - // 4PJ) into the stored assistant turn. PR #3553 threaded the - // signature through the live response→request hop and the - // stored-history *parser* (`parse_provider_tool_call_from_value`), - // but this writer — the single sink the agent loop persists every - // native tool-call turn through (engine/core.rs) — dropped it. On a - // history reload the rebuilt assistant turn therefore lacked - // `extra_content`, so the echoed `functionCall` part went out with - // no `thought_signature` and Gemini 400'd ("Function call is - // missing a thought_signature in functionCall parts"). Write it - // per-part so EVERY call in a parallel/multi-call turn round-trips, - // not just the first; `skip_serializing_if = "Option::is_none"` on - // `extra_content` keeps the stored JSON byte-identical for every - // provider that doesn't emit it. - if let Some(extra) = tc.extra_content.clone() { - if let Some(obj) = call.as_object_mut() { - obj.insert("extra_content".to_string(), extra); - } - } - call - }) - .collect(); - - let content = if text.trim().is_empty() { - serde_json::Value::Null - } else { - serde_json::Value::String(text.trim().to_string()) - }; - - let mut entry = serde_json::json!({ - "content": content, - "tool_calls": calls_json, - }); - - if let Some(reasoning) = reasoning_content.map(str::trim).filter(|r| !r.is_empty()) { - entry["reasoning_content"] = serde_json::Value::String(reasoning.to_string()); - } - - entry.to_string() -} - -#[cfg(test)] -pub(crate) fn build_assistant_history_with_tool_calls( - text: &str, - tool_calls: &[NativeToolCall], -) -> String { - let mut parts = Vec::new(); - - if !text.trim().is_empty() { - parts.push(text.trim().to_string()); - } - - for call in tool_calls { - let arguments = serde_json::from_str::(&call.arguments) - .unwrap_or_else(|_| serde_json::Value::String(call.arguments.clone())); - let payload = serde_json::json!({ - "id": call.id, - "name": call.name, - "arguments": arguments, - }); - parts.push(format!("\n{payload}\n")); - } - - parts.join("\n") -} - -/// Convert a tool registry to OpenAI function-calling format for native tool support. -#[cfg(test)] -pub(crate) fn tools_to_openai_format(tools_registry: &[Box]) -> Vec { - tools_registry - .iter() - .map(|tool| { - serde_json::json!({ - "type": "function", - "function": { - "name": tool.name(), - "description": tool.description(), - "parameters": tool.parameters_schema() - } - }) - }) - .collect() -} - -#[cfg(test)] -#[path = "parse_tests.rs"] -mod tests; diff --git a/crates/openhuman-core/src/agent/learning/prompt_sections_tests_2_tests.rs b/crates/openhuman-core/src/agent/learning/prompt_sections_tests_2_tests.rs index 88c0318d2ea..3e959e03329 100644 --- a/crates/openhuman-core/src/agent/learning/prompt_sections_tests_2_tests.rs +++ b/crates/openhuman-core/src/agent/learning/prompt_sections_tests_2_tests.rs @@ -1,69 +1,11 @@ use super::*; use crate::agent::prompts::LearnedContextData; -use crate::memory::{Memory, MemoryCategory, MemoryEntry}; +use crate::memory::test_support::NoopMemory; use async_trait::async_trait; use std::collections::HashSet; use std::path::Path; use std::sync::Arc; -struct NoopMemory; - -#[async_trait] -impl Memory for NoopMemory { - fn name(&self) -> &str { - "noop" - } - - async fn store( - &self, - _namespace: &str, - _key: &str, - _content: &str, - _category: MemoryCategory, - _session_id: Option<&str>, - ) -> anyhow::Result<()> { - Ok(()) - } - - async fn recall( - &self, - _query: &str, - _limit: usize, - _opts: crate::memory::RecallOpts<'_>, - ) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn get(&self, _namespace: &str, _key: &str) -> anyhow::Result> { - Ok(None) - } - - async fn list( - &self, - _namespace: Option<&str>, - _category: Option<&MemoryCategory>, - _session_id: Option<&str>, - ) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn forget(&self, _namespace: &str, _key: &str) -> anyhow::Result { - Ok(false) - } - - async fn namespace_summaries(&self) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn count(&self) -> anyhow::Result { - Ok(0) - } - - async fn health_check(&self) -> bool { - true - } -} - fn prompt_context(learned: LearnedContextData) -> PromptContext<'static> { let visible_tool_names = Box::leak(Box::new(HashSet::new())); PromptContext { diff --git a/crates/openhuman-core/src/agent/learning/reflection_tests.rs b/crates/openhuman-core/src/agent/learning/reflection_tests.rs index ce841467a6e..aac19ae9d74 100644 --- a/crates/openhuman-core/src/agent/learning/reflection_tests.rs +++ b/crates/openhuman-core/src/agent/learning/reflection_tests.rs @@ -1,86 +1,9 @@ use super::*; use crate::agent::hooks::{ToolCallRecord, TurnContext}; -use crate::memory::{Memory, MemoryCategory, MemoryEntry}; -use async_trait::async_trait; -use parking_lot::Mutex; -use std::collections::HashMap; +use crate::memory::test_support::RetainingMemory; +use crate::memory::{Memory, MemoryCategory}; use std::sync::Arc; -#[derive(Default)] -struct MockMemory { - entries: Mutex>, -} - -#[async_trait] -impl Memory for MockMemory { - fn name(&self) -> &str { - "mock" - } - - async fn store( - &self, - namespace: &str, - key: &str, - content: &str, - category: MemoryCategory, - session_id: Option<&str>, - ) -> anyhow::Result<()> { - self.entries.lock().insert( - key.to_string(), - MemoryEntry { - id: key.to_string(), - key: key.to_string(), - content: content.to_string(), - namespace: Some(namespace.to_string()), - category, - timestamp: "now".into(), - session_id: session_id.map(str::to_string), - score: None, - taint: Default::default(), - }, - ); - Ok(()) - } - - async fn recall( - &self, - _query: &str, - _limit: usize, - _opts: crate::memory::RecallOpts<'_>, - ) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn get(&self, _namespace: &str, key: &str) -> anyhow::Result> { - Ok(self.entries.lock().get(key).cloned()) - } - - async fn list( - &self, - _namespace: Option<&str>, - _category: Option<&MemoryCategory>, - _session_id: Option<&str>, - ) -> anyhow::Result> { - Ok(self.entries.lock().values().cloned().collect()) - } - - async fn forget(&self, _namespace: &str, key: &str) -> anyhow::Result { - Ok(self.entries.lock().remove(key).is_some()) - } - - async fn namespace_summaries(&self) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn count(&self) -> anyhow::Result { - Ok(self.entries.lock().len()) - } - - async fn health_check(&self) -> bool { - true - } -} - fn reflection_config() -> LearningConfig { LearningConfig { enabled: true, @@ -145,7 +68,7 @@ fn slugify_produces_clean_keys() { #[test] fn should_reflect_requires_learning_and_complexity() { - let memory: Arc = Arc::new(MockMemory::default()); + let memory: Arc = Arc::new(RetainingMemory::default()); let hook = ReflectionHook::new( reflection_config(), Arc::new(Config::default()), @@ -159,7 +82,7 @@ fn should_reflect_requires_learning_and_complexity() { let hook = ReflectionHook::new( disabled, Arc::new(Config::default()), - Arc::new(MockMemory::default()), + Arc::new(RetainingMemory::default()), None, ); assert!(!hook.should_reflect(&reflective_turn())); @@ -170,7 +93,7 @@ fn should_reflect_requires_learning_and_complexity() { let hook = ReflectionHook::new( reflection_config(), Arc::new(Config::default()), - Arc::new(MockMemory::default()), + Arc::new(RetainingMemory::default()), None, ); assert!(!hook.should_reflect(&simple)); @@ -178,7 +101,7 @@ fn should_reflect_requires_learning_and_complexity() { #[test] fn build_reflection_prompt_includes_tool_calls_and_truncation() { - let memory: Arc = Arc::new(MockMemory::default()); + let memory: Arc = Arc::new(RetainingMemory::default()); let hook = ReflectionHook::new( reflection_config(), Arc::new(Config::default()), @@ -203,7 +126,7 @@ fn build_reflection_prompt_includes_tool_calls_and_truncation() { #[test] fn build_reflection_prompt_includes_output_language_directive() { - let memory: Arc = Arc::new(MockMemory::default()); + let memory: Arc = Arc::new(RetainingMemory::default()); let mut config = Config::default(); config.output_language = Some("zh-CN".into()); let hook = ReflectionHook::new(reflection_config(), Arc::new(config), memory, None); @@ -219,7 +142,7 @@ fn session_key_and_counter_management_work() { let hook = ReflectionHook::new( reflection_config(), Arc::new(Config::default()), - Arc::new(MockMemory::default()), + Arc::new(RetainingMemory::default()), None, ); @@ -238,7 +161,7 @@ fn session_key_and_counter_management_work() { #[tokio::test] async fn store_reflection_persists_all_categories() { - let memory_impl = Arc::new(MockMemory::default()); + let memory_impl = Arc::new(RetainingMemory::default()); let memory: Arc = memory_impl.clone(); let hook = ReflectionHook::new( reflection_config(), @@ -262,7 +185,13 @@ async fn store_reflection_persists_all_categories() { .await .unwrap(); - let keys: Vec = memory_impl.entries.lock().keys().cloned().collect(); + let keys: Vec = memory_impl + .list(None, None, None) + .await + .unwrap() + .into_iter() + .map(|e| e.key) + .collect(); assert!(keys.iter().any(|key| key.starts_with("obs/"))); assert!(keys.iter().any(|key| key == "pat/pattern_a")); assert!(keys.iter().any(|key| key == "pref/pref_a")); @@ -277,7 +206,7 @@ async fn store_reflection_persists_every_pattern_and_pref_concurrently() { // Regression guard for the `join_all` batching: every independent // pattern / preference write must land regardless of completion order // (the old code awaited them one at a time). - let memory_impl = Arc::new(MockMemory::default()); + let memory_impl = Arc::new(RetainingMemory::default()); let memory: Arc = memory_impl.clone(); let hook = ReflectionHook::new( reflection_config(), @@ -299,7 +228,13 @@ async fn store_reflection_persists_every_pattern_and_pref_concurrently() { .await .unwrap(); - let keys: Vec = memory_impl.entries.lock().keys().cloned().collect(); + let keys: Vec = memory_impl + .list(None, None, None) + .await + .unwrap() + .into_iter() + .map(|e| e.key) + .collect(); for expected in [ "pat/pattern_one", "pat/pattern_two", @@ -321,7 +256,7 @@ async fn store_reflection_persists_every_pattern_and_pref_concurrently() { #[tokio::test] async fn persist_reflection_writes_to_dedicated_namespace_and_category() { - let memory_impl = Arc::new(MockMemory::default()); + let memory_impl = Arc::new(RetainingMemory::default()); let memory: Arc = memory_impl.clone(); let hook = ReflectionHook::new( reflection_config(), @@ -334,9 +269,9 @@ async fn persist_reflection_writes_to_dedicated_namespace_and_category() { .await .unwrap(); - let entries = memory_impl.entries.lock(); + let entries = memory_impl.list(None, None, None).await.unwrap(); let reflection = entries - .values() + .iter() .find(|e| e.key.starts_with("ref/")) .expect("reflection entry"); assert_eq!(reflection.namespace.as_deref(), Some(REFLECTIONS_NAMESPACE)); @@ -353,7 +288,7 @@ async fn on_turn_complete_dedupes_reflections_across_heuristic_and_llm_paths() { // `user_reflections` array repeats the same sentence the heuristic // would also lift out of the user message. - let memory_impl = Arc::new(MockMemory::default()); + let memory_impl = Arc::new(RetainingMemory::default()); let memory: Arc = memory_impl.clone(); let stub_model = Arc::new(tinyagents_harness::testkit::ScriptedModel::replies(vec![ r#"{"observations":[],"patterns":[],"user_preferences":[], @@ -382,9 +317,10 @@ async fn on_turn_complete_dedupes_reflections_across_heuristic_and_llm_paths() { hook.on_turn_complete(&turn).await.unwrap(); let ref_count = memory_impl - .entries - .lock() - .values() + .list(None, None, None) + .await + .unwrap() + .iter() .filter(|e| e.key.starts_with("ref/")) .count(); assert_eq!( @@ -435,7 +371,7 @@ fn extract_reflection_cues_dedupes_identical_sentences() { #[tokio::test] async fn on_turn_complete_persists_heuristic_reflection_even_when_complexity_low() { - let memory_impl = Arc::new(MockMemory::default()); + let memory_impl = Arc::new(RetainingMemory::default()); let memory: Arc = memory_impl.clone(); // Pin the source to local + threshold high so the LLM path is // skipped and we observe ONLY the heuristic capture. @@ -458,7 +394,13 @@ async fn on_turn_complete_persists_heuristic_reflection_even_when_complexity_low // even without a provider — only the heuristic should write. hook.on_turn_complete(&turn).await.unwrap(); - let keys: Vec = memory_impl.entries.lock().keys().cloned().collect(); + let keys: Vec = memory_impl + .list(None, None, None) + .await + .unwrap() + .into_iter() + .map(|e| e.key) + .collect(); assert!( keys.iter().any(|k| k.starts_with("ref/")), "heuristic capture should persist a reflection without LLM round-trip" @@ -467,7 +409,7 @@ async fn on_turn_complete_persists_heuristic_reflection_even_when_complexity_low #[tokio::test] async fn on_turn_complete_rolls_back_counter_when_reflection_call_fails() { - let memory: Arc = Arc::new(MockMemory::default()); + let memory: Arc = Arc::new(RetainingMemory::default()); let hook = ReflectionHook::new( reflection_config(), Arc::new(Config::default()), @@ -492,7 +434,7 @@ async fn on_turn_complete_rolls_back_counter_when_reflection_call_fails() { async fn on_turn_complete_emits_candidates_to_buffer_for_heuristic_cues() { use crate::agent::learning::candidate::{self, FacetClass}; - let memory: Arc = Arc::new(MockMemory::default()); + let memory: Arc = Arc::new(RetainingMemory::default()); // Use local reflection source with complexity gated high so only the heuristic // fast-path runs (no LLM round-trip needed). let mut cfg = reflection_config(); @@ -532,7 +474,7 @@ async fn on_turn_complete_emits_candidates_to_buffer_for_heuristic_cues() { async fn on_turn_complete_emits_style_candidates_from_llm_preferences() { use crate::agent::learning::candidate::{self, FacetClass}; - let memory: Arc = Arc::new(MockMemory::default()); + let memory: Arc = Arc::new(RetainingMemory::default()); let stub_model = Arc::new(tinyagents_harness::testkit::ScriptedModel::replies(vec![ r#"{"observations":[],"patterns":[],"user_preferences":["verbosity=terse"],"user_reflections":[]}"#, ])); diff --git a/crates/openhuman-core/src/agent/learning/schemas_tests.rs b/crates/openhuman-core/src/agent/learning/schemas_tests.rs index 41cb3e25e3a..178a9bee348 100644 --- a/crates/openhuman-core/src/agent/learning/schemas_tests.rs +++ b/crates/openhuman-core/src/agent/learning/schemas_tests.rs @@ -2,13 +2,20 @@ use super::*; use serde_json::{Map, Value}; #[test] -fn all_schemas_returns_eleven() { - assert_eq!(all_learning_controller_schemas().len(), 11); +fn schema_and_controller_registries_agree_on_eleven_entries() { + let s = all_learning_controller_schemas(); + let c = all_learning_registered_controllers(); + assert_eq!(s.len(), 11); + assert_eq!(c.len(), 11); + assert_eq!(s[0].function, c[0].schema.function); } #[test] -fn all_controllers_returns_eleven() { - assert_eq!(all_learning_registered_controllers().len(), 11); +fn facet_state_change_schemas_are_registered_under_their_function_names() { + for function in ["pin_facet", "unpin_facet", "forget_facet"] { + let s = learning_schemas(&format!("learning_{function}")); + assert_eq!(s.function, function); + } } #[test] @@ -85,13 +92,6 @@ fn facet_to_json_includes_cue_families_and_evidence_refs() { assert!(json["cue_families"].is_null()); } -#[test] -fn schemas_and_controllers_match() { - let s = all_learning_controller_schemas(); - let c = all_learning_registered_controllers(); - assert_eq!(s[0].function, c[0].schema.function); -} - #[test] fn list_facets_schema_shape() { let s = learning_schemas("learning_list_facets"); @@ -117,24 +117,6 @@ fn update_facet_schema_shape() { assert!(s.inputs.iter().any(|f| f.name == "value" && f.required)); } -#[test] -fn pin_facet_schema_shape() { - let s = learning_schemas("learning_pin_facet"); - assert_eq!(s.function, "pin_facet"); -} - -#[test] -fn unpin_facet_schema_shape() { - let s = learning_schemas("learning_unpin_facet"); - assert_eq!(s.function, "unpin_facet"); -} - -#[test] -fn forget_facet_schema_shape() { - let s = learning_schemas("learning_forget_facet"); - assert_eq!(s.function, "forget_facet"); -} - #[test] fn reset_cache_schema_shape() { let s = learning_schemas("learning_reset_cache"); diff --git a/crates/openhuman-core/src/agent/learning/tool_tracker_tests.rs b/crates/openhuman-core/src/agent/learning/tool_tracker_tests.rs index 4cc743ec81f..124df2da041 100644 --- a/crates/openhuman-core/src/agent/learning/tool_tracker_tests.rs +++ b/crates/openhuman-core/src/agent/learning/tool_tracker_tests.rs @@ -1,86 +1,9 @@ use super::*; use crate::agent::hooks::{ToolCallRecord, TurnContext}; -use crate::memory::{Memory, MemoryCategory, MemoryEntry}; -use async_trait::async_trait; -use parking_lot::Mutex; -use std::collections::HashMap; +use crate::memory::test_support::RetainingMemory; +use crate::memory::{Memory, MemoryCategory}; use std::sync::Arc; -#[derive(Default)] -struct MockMemory { - entries: Mutex>, -} - -#[async_trait] -impl Memory for MockMemory { - fn name(&self) -> &str { - "mock" - } - - async fn store( - &self, - namespace: &str, - key: &str, - content: &str, - category: MemoryCategory, - session_id: Option<&str>, - ) -> anyhow::Result<()> { - self.entries.lock().insert( - key.to_string(), - MemoryEntry { - id: key.to_string(), - key: key.to_string(), - content: content.to_string(), - namespace: Some(namespace.to_string()), - category, - timestamp: "now".into(), - session_id: session_id.map(str::to_string), - score: None, - taint: Default::default(), - }, - ); - Ok(()) - } - - async fn recall( - &self, - _query: &str, - _limit: usize, - _opts: crate::memory::RecallOpts<'_>, - ) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn get(&self, _namespace: &str, key: &str) -> anyhow::Result> { - Ok(self.entries.lock().get(key).cloned()) - } - - async fn list( - &self, - _namespace: Option<&str>, - _category: Option<&MemoryCategory>, - _session_id: Option<&str>, - ) -> anyhow::Result> { - Ok(self.entries.lock().values().cloned().collect()) - } - - async fn forget(&self, _namespace: &str, key: &str) -> anyhow::Result { - Ok(self.entries.lock().remove(key).is_some()) - } - - async fn namespace_summaries(&self) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn count(&self) -> anyhow::Result { - Ok(self.entries.lock().len()) - } - - async fn health_check(&self) -> bool { - true - } -} - #[test] fn tool_stats_record_call_updates_correctly() { let mut stats = ToolStats::default(); @@ -131,7 +54,7 @@ fn tool_stats_keeps_only_recent_unique_error_patterns() { #[tokio::test] async fn update_stats_merges_with_existing_memory_entry() { - let memory_impl = Arc::new(MockMemory::default()); + let memory_impl = Arc::new(RetainingMemory::default()); memory_impl .store( "tool_effectiveness", @@ -176,7 +99,7 @@ async fn update_stats_merges_with_existing_memory_entry() { #[tokio::test] async fn on_turn_complete_skips_when_disabled_or_no_tools() { - let memory_impl = Arc::new(MockMemory::default()); + let memory_impl = Arc::new(RetainingMemory::default()); let memory: Arc = memory_impl.clone(); let hook = ToolTrackerHook::new(LearningConfig::default(), memory); let ctx = TurnContext { @@ -191,12 +114,12 @@ async fn on_turn_complete_skips_when_disabled_or_no_tools() { }; hook.on_turn_complete(&ctx).await.unwrap(); - assert!(memory_impl.entries.lock().is_empty()); + assert!(memory_impl.list(None, None, None).await.unwrap().is_empty()); } #[tokio::test] async fn on_turn_complete_records_each_tool_call() { - let memory_impl = Arc::new(MockMemory::default()); + let memory_impl = Arc::new(RetainingMemory::default()); let memory: Arc = memory_impl.clone(); let hook = ToolTrackerHook::new( LearningConfig { diff --git a/crates/openhuman-core/src/agent/learning/user_profile_tests.rs b/crates/openhuman-core/src/agent/learning/user_profile_tests.rs index 56fe8569245..32fa36cd58e 100644 --- a/crates/openhuman-core/src/agent/learning/user_profile_tests.rs +++ b/crates/openhuman-core/src/agent/learning/user_profile_tests.rs @@ -1,86 +1,9 @@ use super::*; use crate::agent::hooks::TurnContext; -use crate::memory::{Memory, MemoryCategory, MemoryEntry}; -use async_trait::async_trait; -use parking_lot::Mutex; -use std::collections::HashMap; +use crate::memory::test_support::RetainingMemory; +use crate::memory::{Memory, MemoryCategory}; use std::sync::Arc; -#[derive(Default)] -struct MockMemory { - entries: Mutex>, -} - -#[async_trait] -impl Memory for MockMemory { - fn name(&self) -> &str { - "mock" - } - - async fn store( - &self, - namespace: &str, - key: &str, - content: &str, - category: MemoryCategory, - session_id: Option<&str>, - ) -> anyhow::Result<()> { - self.entries.lock().insert( - key.to_string(), - MemoryEntry { - id: key.to_string(), - key: key.to_string(), - content: content.to_string(), - namespace: Some(namespace.to_string()), - category, - timestamp: "now".into(), - session_id: session_id.map(str::to_string), - score: None, - taint: Default::default(), - }, - ); - Ok(()) - } - - async fn recall( - &self, - _query: &str, - _limit: usize, - _opts: crate::memory::RecallOpts<'_>, - ) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn get(&self, _namespace: &str, key: &str) -> anyhow::Result> { - Ok(self.entries.lock().get(key).cloned()) - } - - async fn list( - &self, - _namespace: Option<&str>, - _category: Option<&MemoryCategory>, - _session_id: Option<&str>, - ) -> anyhow::Result> { - Ok(self.entries.lock().values().cloned().collect()) - } - - async fn forget(&self, _namespace: &str, key: &str) -> anyhow::Result { - Ok(self.entries.lock().remove(key).is_some()) - } - - async fn namespace_summaries(&self) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn count(&self) -> anyhow::Result { - Ok(self.entries.lock().len()) - } - - async fn health_check(&self) -> bool { - true - } -} - #[test] fn extract_preferences_finds_patterns() { let msg = "I prefer Rust over Python. Always use snake_case for variables."; @@ -286,7 +209,7 @@ fn preference_dfa_compiles_and_has_expected_pattern_count() { #[tokio::test] async fn store_preferences_skips_duplicates_and_empty_slugs() { - let memory_impl = Arc::new(MockMemory::default()); + let memory_impl = Arc::new(RetainingMemory::default()); memory_impl .store( "user_profile", @@ -315,7 +238,13 @@ async fn store_preferences_skips_duplicates_and_empty_slugs() { .await .unwrap(); - let keys: Vec = memory_impl.entries.lock().keys().cloned().collect(); + let keys: Vec = memory_impl + .list(None, None, None) + .await + .unwrap() + .into_iter() + .map(|e| e.key) + .collect(); assert_eq!(keys.len(), 2); assert!(keys.contains(&"pref/i_prefer_rust".into())); assert!(keys.contains(&"pref/my_timezone_is_pst".into())); @@ -323,7 +252,7 @@ async fn store_preferences_skips_duplicates_and_empty_slugs() { #[tokio::test] async fn on_turn_complete_respects_feature_flags_and_stores_preferences() { - let memory_impl = Arc::new(MockMemory::default()); + let memory_impl = Arc::new(RetainingMemory::default()); let memory: Arc = memory_impl.clone(); let ctx = TurnContext { user_message: "My language is English. Please always use concise output.".into(), @@ -338,7 +267,7 @@ async fn on_turn_complete_respects_feature_flags_and_stores_preferences() { let disabled = UserProfileHook::new(LearningConfig::default(), memory.clone()); disabled.on_turn_complete(&ctx).await.unwrap(); - assert!(memory_impl.entries.lock().is_empty()); + assert!(memory_impl.list(None, None, None).await.unwrap().is_empty()); let enabled = UserProfileHook::new( LearningConfig { @@ -351,9 +280,10 @@ async fn on_turn_complete_respects_feature_flags_and_stores_preferences() { enabled.on_turn_complete(&ctx).await.unwrap(); let values: Vec = memory_impl - .entries - .lock() - .values() + .list(None, None, None) + .await + .unwrap() + .iter() .map(|entry| entry.content.clone()) .collect(); assert!(values diff --git a/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime_tests.rs b/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime_tests.rs index ba8d4f76c6e..70afdfe52a5 100644 --- a/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime_tests.rs +++ b/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime_tests.rs @@ -8,6 +8,7 @@ //! real entry point; its `Started` path (which spawns a loop building a real //! `Agent` from config) is covered by the JSON-RPC e2e over the live core stack. +use crate::memory::test_support::NoopMemory; use std::collections::HashSet; use std::sync::Arc; @@ -18,7 +19,6 @@ use crate::agent::harness::definition::AgentDefinitionRegistry; use crate::agent::harness::fork_context::{with_parent_context, ParentExecutionContext}; use crate::agent::prompts::ToolCallFormat; use crate::config::{AgentConfig, Config}; -use crate::memory::{Memory, MemoryCategory, MemoryEntry, NamespaceSummary, RecallOpts}; use tinyagents_orchestration::teams::{SessionTeamLedger, TeamService}; use tinyagents_session::run_ledger::{ self, AgentTeamMemberStatus, AgentTeamMemberUpsert, AgentTeamStatus, AgentTeamTaskStatus, @@ -29,57 +29,6 @@ use tinytools::Tool; // ── Mocks (mirror workflow_runs::engine_tests) ────────────────────────────── -#[derive(Default)] -struct NoopMemory; - -#[async_trait] -impl Memory for NoopMemory { - async fn store( - &self, - _ns: &str, - _key: &str, - _content: &str, - _cat: MemoryCategory, - _sid: Option<&str>, - ) -> anyhow::Result<()> { - Ok(()) - } - async fn recall( - &self, - _q: &str, - _l: usize, - _o: RecallOpts<'_>, - ) -> anyhow::Result> { - Ok(Vec::new()) - } - async fn get(&self, _ns: &str, _key: &str) -> anyhow::Result> { - Ok(None) - } - async fn list( - &self, - _ns: Option<&str>, - _cat: Option<&MemoryCategory>, - _sid: Option<&str>, - ) -> anyhow::Result> { - Ok(Vec::new()) - } - async fn forget(&self, _ns: &str, _key: &str) -> anyhow::Result { - Ok(false) - } - async fn namespace_summaries(&self) -> anyhow::Result> { - Ok(Vec::new()) - } - async fn count(&self) -> anyhow::Result { - Ok(0) - } - async fn health_check(&self) -> bool { - true - } - fn name(&self) -> &str { - "noop" - } -} - fn text_response(text: impl Into) -> ModelResponse { ModelResponse::assistant(text) } diff --git a/crates/openhuman-core/src/agent/orchestration/ops_tests.rs b/crates/openhuman-core/src/agent/orchestration/ops_tests.rs index eefde894450..436f21377fd 100644 --- a/crates/openhuman-core/src/agent/orchestration/ops_tests.rs +++ b/crates/openhuman-core/src/agent/orchestration/ops_tests.rs @@ -3,7 +3,7 @@ use crate::agent::harness::definition::AgentDefinitionRegistry; use crate::agent::harness::fork_context::{with_parent_context, ParentExecutionContext}; use crate::agent::prompts::ToolCallFormat; use crate::config::AgentConfig; -use crate::memory::{Memory, MemoryCategory, MemoryEntry, NamespaceSummary, RecallOpts}; +use crate::memory::test_support::NoopMemory; use async_trait::async_trait; use parking_lot::Mutex; use std::future::Future; @@ -15,65 +15,6 @@ use tinyinference_llm::model::{ChatModel, ModelProfile, ModelRequest, ModelRespo use tinytools::Tool; use tokio::time::Duration; -#[derive(Default)] -struct NoopMemory; - -#[async_trait] -impl Memory for NoopMemory { - async fn store( - &self, - _namespace: &str, - _key: &str, - _content: &str, - _category: MemoryCategory, - _session_id: Option<&str>, - ) -> anyhow::Result<()> { - Ok(()) - } - - async fn recall( - &self, - _query: &str, - _limit: usize, - _opts: RecallOpts<'_>, - ) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn get(&self, _namespace: &str, _key: &str) -> anyhow::Result> { - Ok(None) - } - - async fn list( - &self, - _namespace: Option<&str>, - _category: Option<&MemoryCategory>, - _session_id: Option<&str>, - ) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn forget(&self, _namespace: &str, _key: &str) -> anyhow::Result { - Ok(false) - } - - async fn namespace_summaries(&self) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn count(&self) -> anyhow::Result { - Ok(0) - } - - async fn health_check(&self) -> bool { - true - } - - fn name(&self) -> &str { - "noop" - } -} - fn parent_context(model: Arc>) -> ParentExecutionContext { ParentExecutionContext { workspace_descriptor: None, diff --git a/crates/openhuman-core/src/agent/orchestration/tools/close_subagent_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/close_subagent_tests.rs index 29edbd85d63..0461fb8912c 100644 --- a/crates/openhuman-core/src/agent/orchestration/tools/close_subagent_tests.rs +++ b/crates/openhuman-core/src/agent/orchestration/tools/close_subagent_tests.rs @@ -2,7 +2,7 @@ use super::*; use crate::agent::harness::fork_context::ParentExecutionContext; use crate::agent::prompts::ToolCallFormat; use crate::config::AgentConfig; -use crate::memory::{Memory, MemoryCategory, MemoryEntry, NamespaceSummary, RecallOpts}; +use crate::memory::test_support::NoopMemory; use std::collections::HashSet; use std::path::Path; use std::sync::Arc; @@ -131,61 +131,3 @@ fn parent_context(workspace_dir: &Path) -> ParentExecutionContext { run_queue: None, } } - -struct NoopMemory; - -#[async_trait::async_trait] -impl Memory for NoopMemory { - fn name(&self) -> &str { - "noop" - } - - async fn store( - &self, - _namespace: &str, - _key: &str, - _content: &str, - _category: MemoryCategory, - _session_id: Option<&str>, - ) -> anyhow::Result<()> { - Ok(()) - } - - async fn recall( - &self, - _query: &str, - _limit: usize, - _opts: RecallOpts<'_>, - ) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn get(&self, _namespace: &str, _key: &str) -> anyhow::Result> { - Ok(None) - } - - async fn list( - &self, - _namespace: Option<&str>, - _category: Option<&MemoryCategory>, - _session_id: Option<&str>, - ) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn forget(&self, _namespace: &str, _key: &str) -> anyhow::Result { - Ok(false) - } - - async fn namespace_summaries(&self) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn count(&self) -> anyhow::Result { - Ok(0) - } - - async fn health_check(&self) -> bool { - true - } -} diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_tests.rs index 8de9dd7bab7..f3fe4c5ffc5 100644 --- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_tests.rs +++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_tests.rs @@ -3,7 +3,7 @@ use crate::agent::harness::definition::AgentDefinitionRegistry; use crate::agent::harness::fork_context::{with_parent_context, ParentExecutionContext}; use crate::agent::prompts::ToolCallFormat; use crate::config::AgentConfig; -use crate::memory::{Memory, MemoryCategory, MemoryEntry, NamespaceSummary, RecallOpts}; +use crate::memory::test_support::NoopMemory; use std::collections::HashSet; use std::path::Path; use std::sync::Arc; @@ -485,64 +485,6 @@ fn parent_context(workspace_dir: &Path) -> ParentExecutionContext { } } -struct NoopMemory; - -#[async_trait::async_trait] -impl Memory for NoopMemory { - fn name(&self) -> &str { - "noop" - } - - async fn store( - &self, - _namespace: &str, - _key: &str, - _content: &str, - _category: MemoryCategory, - _session_id: Option<&str>, - ) -> anyhow::Result<()> { - Ok(()) - } - - async fn recall( - &self, - _query: &str, - _limit: usize, - _opts: RecallOpts<'_>, - ) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn get(&self, _namespace: &str, _key: &str) -> anyhow::Result> { - Ok(None) - } - - async fn list( - &self, - _namespace: Option<&str>, - _category: Option<&MemoryCategory>, - _session_id: Option<&str>, - ) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn forget(&self, _namespace: &str, _key: &str) -> anyhow::Result { - Ok(false) - } - - async fn namespace_summaries(&self) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn count(&self) -> anyhow::Result { - Ok(0) - } - - async fn health_check(&self) -> bool { - true - } -} - /// The session builder swaps in a scoped instance so the WIRE schema (read /// from the registered tool on native tool calling) carries only the ids the /// parent may dispatch, sorted and deduplicated, and says so. diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs index 7f217e76cee..d2ebdb2950b 100644 --- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs +++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs @@ -13,7 +13,8 @@ use crate::agent::prompts::ToolCallFormat; use crate::agent::tinyagents::host::OpenHumanRunContext; use crate::agent::OpenHumanSessionHost; use crate::config::AgentConfig; -use crate::memory::{Memory, MemoryCategory, MemoryEntry, NamespaceSummary, RecallOpts}; +use crate::memory::test_support::NoopMemory; +use crate::memory::Memory; use async_trait::async_trait; use parking_lot::Mutex; use serde_json::json; @@ -46,64 +47,6 @@ fn test_lineage(task_id: &str) -> ParallelAgentLineage { } } -struct NoopMemory; - -#[async_trait] -impl Memory for NoopMemory { - async fn store( - &self, - _namespace: &str, - _key: &str, - _content: &str, - _category: MemoryCategory, - _session_id: Option<&str>, - ) -> anyhow::Result<()> { - Ok(()) - } - - async fn recall( - &self, - _query: &str, - _limit: usize, - _opts: RecallOpts<'_>, - ) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn get(&self, _namespace: &str, _key: &str) -> anyhow::Result> { - Ok(None) - } - - async fn list( - &self, - _namespace: Option<&str>, - _category: Option<&MemoryCategory>, - _session_id: Option<&str>, - ) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn forget(&self, _namespace: &str, _key: &str) -> anyhow::Result { - Ok(false) - } - - async fn namespace_summaries(&self) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn count(&self) -> anyhow::Result { - Ok(0) - } - - async fn health_check(&self) -> bool { - true - } - - fn name(&self) -> &str { - "noop" - } -} - fn parent_context(max_parallel_tools: usize) -> ParentExecutionContext { let agent_config = AgentConfig { max_parallel_tools, diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tests.rs index 6d67f4a0a8b..c440b284996 100644 --- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tests.rs +++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tests.rs @@ -40,6 +40,11 @@ fn parameters_schema_advertises_dedicated_thread_flag() { let tool = SpawnSubagentTool; let schema = tool.parameters_schema(); let props = schema.get("properties").expect("schema has properties"); + // The per-toolkit spawn argument went with the integrations specialist. + assert!( + props.get("toolkit").is_none(), + "spawn_subagent must not advertise the removed `toolkit` argument" + ); let flag = props .get("dedicated_thread") .expect("dedicated_thread advertised"); diff --git a/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_tests.rs index 245209947bf..a71b1f15342 100644 --- a/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_tests.rs +++ b/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_tests.rs @@ -4,7 +4,7 @@ use crate::agent::harness::{with_parent_context, ParentExecutionContext}; use crate::agent::messages::ChatMessage; use crate::agent::prompts::{ConnectedIntegration, ToolCallFormat}; use crate::memory::conversations; -use crate::memory::{Memory, MemoryCategory, MemoryEntry, NamespaceSummary, RecallOpts}; +use crate::memory::test_support::NoopMemory; use async_trait::async_trait; use parking_lot::Mutex; use serde_json::json; @@ -500,61 +500,3 @@ fn flatten_messages(messages: &[Message]) -> String { .collect::>() .join("\n") } - -struct NoopMemory; - -#[async_trait] -impl Memory for NoopMemory { - async fn store( - &self, - _namespace: &str, - _key: &str, - _value: &str, - _category: MemoryCategory, - _source: Option<&str>, - ) -> anyhow::Result<()> { - Ok(()) - } - - async fn recall( - &self, - _query: &str, - _limit: usize, - _opts: RecallOpts<'_>, - ) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn get(&self, _namespace: &str, _key: &str) -> anyhow::Result> { - Ok(None) - } - - async fn list( - &self, - _namespace: Option<&str>, - _category: Option<&MemoryCategory>, - _source: Option<&str>, - ) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn forget(&self, _namespace: &str, _key: &str) -> anyhow::Result { - Ok(false) - } - - async fn namespace_summaries(&self) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn count(&self) -> anyhow::Result { - Ok(0) - } - - async fn health_check(&self) -> bool { - true - } - - fn name(&self) -> &str { - "noop" - } -} diff --git a/crates/openhuman-core/src/agent/prompts/mod_tests_subagent_render_tests.rs b/crates/openhuman-core/src/agent/prompts/mod_tests_subagent_render_tests.rs index d7fe0e3970a..e4c40bfee79 100644 --- a/crates/openhuman-core/src/agent/prompts/mod_tests_subagent_render_tests.rs +++ b/crates/openhuman-core/src/agent/prompts/mod_tests_subagent_render_tests.rs @@ -195,457 +195,148 @@ fn render_subagent_system_prompt_honors_identity_safety_and_skills_flags() { let _ = std::fs::remove_dir_all(workspace); } -#[test] -fn render_subagent_system_prompt_injects_profile_md_even_when_identity_omitted() { - // Regression: an agent with `omit_identity = true` drops the SOUL/IDENTITY - // preamble but still needs PROFILE.md if `include_profile = true`. - // PROFILE.md is gated on its own flag so agents can opt in without - // pulling SOUL/IDENTITY back in. - let workspace = std::env::temp_dir().join(format!( - "openhuman_prompt_profile_nosoul_{}", - uuid::Uuid::new_v4() - )); - std::fs::create_dir_all(&workspace).unwrap(); - std::fs::write(workspace.join("SOUL.md"), "# Soul\nShould be hidden").unwrap(); - std::fs::write( - workspace.join("IDENTITY.md"), - "# Identity\nShould be hidden", - ) - .unwrap(); - std::fs::write( - workspace.join("PROFILE.md"), - "# User Profile\nName: Jane Doe\nRole: Data scientist", - ) - .unwrap(); - +/// Render a sub-agent prompt over a scratch workspace holding `files`, with the +/// PFormat tool-call format and the single `TestTool`. +fn render_with_files(files: &[(&str, &str)], options: SubagentRenderOptions) -> String { + let workspace = tempfile::tempdir().expect("tempdir"); + for (name, body) in files { + std::fs::write(workspace.path().join(name), body).unwrap(); + } let tools: Vec> = vec![Box::new(TestTool)]; - let rendered = render_subagent_system_prompt( - &workspace, + render_subagent_system_prompt( + workspace.path(), "test-model", &[0], &tools, &[], "You are a specialist agent.", - SubagentRenderOptions { - include_identity: false, - include_safety_preamble: false, - include_profile: true, - include_memory_md: false, - }, + options, ToolCallFormat::PFormat, &[], - ); - - assert!( - rendered.contains("### PROFILE.md"), - "PROFILE.md header must appear when include_profile=true, got:\n{rendered}" - ); - assert!( - rendered.contains("Jane Doe"), - "PROFILE.md body must be injected when include_profile=true, got:\n{rendered}" - ); - assert!( - !rendered.contains("## Project Context"), - "identity preamble must still be suppressed when include_identity=false" - ); - assert!( - !rendered.contains("### SOUL.md") && !rendered.contains("### IDENTITY.md"), - "SOUL/IDENTITY must still be suppressed when include_identity=false" - ); - - let _ = std::fs::remove_dir_all(workspace); -} - -#[test] -fn render_subagent_system_prompt_skips_profile_md_when_include_profile_false() { - // Mirror of the opt-in regression above: narrow specialists - // (planner, code_executor, critic, …) set `omit_profile = true` - // and must NOT see PROFILE.md even when the file is on disk — - // otherwise every sub-agent pays the token cost of onboarding - // enrichment output that is irrelevant to their task. - let workspace = std::env::temp_dir().join(format!( - "openhuman_prompt_profile_opt_out_{}", - uuid::Uuid::new_v4() - )); - std::fs::create_dir_all(&workspace).unwrap(); - std::fs::write( - workspace.join("PROFILE.md"), - "# User Profile\nName: Jane Doe\nRole: Data scientist", ) - .unwrap(); - - let tools: Vec> = vec![Box::new(TestTool)]; - let rendered = render_subagent_system_prompt( - &workspace, - "test-model", - &[0], - &tools, - &[], - "You are a narrow specialist.", - SubagentRenderOptions::narrow(), // include_profile defaults to false - ToolCallFormat::PFormat, - &[], - ); - - assert!( - !rendered.contains("### PROFILE.md"), - "PROFILE.md must NOT appear when include_profile=false, got:\n{rendered}" - ); - assert!( - !rendered.contains("Jane Doe"), - "PROFILE.md body must NOT be leaked when include_profile=false" - ); - - let _ = std::fs::remove_dir_all(workspace); } -#[test] -fn render_subagent_system_prompt_frames_memory_md_as_background() { - // GH-4745 regression for the sub-agent path: Inline/File sub-agents inject - // MEMORY.md through `render_subagent_system_prompt`, a separate renderer - // from `UserFilesSection`. It must share the same background-memory frame, - // otherwise a fresh thread reads the bare `### MEMORY.md` block as prior - // in-thread conversation and asserts continuity that isn't there. - let workspace = std::env::temp_dir().join(format!( - "openhuman_subagent_memory_framing_{}", - uuid::Uuid::new_v4() - )); - std::fs::create_dir_all(&workspace).unwrap(); - std::fs::write( - workspace.join("MEMORY.md"), - "# Long-term memory\nReviewed `def f(x)` last week; user prefers terse notes.", - ) - .unwrap(); - - let tools: Vec> = vec![Box::new(TestTool)]; - let rendered = render_subagent_system_prompt( - &workspace, - "test-model", - &[0], - &tools, - &[], - "You are a specialist agent.", - SubagentRenderOptions { - include_identity: false, - include_safety_preamble: false, - include_profile: false, - include_memory_md: true, - }, - ToolCallFormat::PFormat, - &[], - ); - - assert!( - rendered.contains("### MEMORY.md") && rendered.contains("terse notes"), - "MEMORY.md must still be injected in the sub-agent path, got:\n{rendered}" - ); - assert!( - rendered.contains("background — not this conversation"), - "sub-agent MEMORY.md must be framed as durable background memory, got:\n{rendered}" - ); - let frame_at = rendered.find("background — not this conversation").unwrap(); - let heading_at = rendered.find("### MEMORY.md").unwrap(); - assert!( - frame_at < heading_at, - "the guardrail note must precede the MEMORY.md block, got:\n{rendered}" - ); - - let _ = std::fs::remove_dir_all(workspace); +fn only(identity: bool, profile: bool, memory: bool) -> SubagentRenderOptions { + SubagentRenderOptions { + include_identity: identity, + include_safety_preamble: false, + include_profile: profile, + include_memory_md: memory, + } } -#[test] -fn render_subagent_system_prompt_omits_memory_framing_when_no_memory_content() { - // Companion to the framing test: with `include_memory_md = true` but no - // MEMORY.md on disk (a genuinely fresh workspace) the dangling frame must - // NOT appear — emitting a "background memory" note pointing at nothing - // would itself imply phantom history. - let workspace = std::env::temp_dir().join(format!( - "openhuman_subagent_memory_noframe_{}", - uuid::Uuid::new_v4() - )); - std::fs::create_dir_all(&workspace).unwrap(); - - let tools: Vec> = vec![Box::new(TestTool)]; - let rendered = render_subagent_system_prompt( - &workspace, - "test-model", - &[0], - &tools, - &[], - "You are a specialist agent.", - SubagentRenderOptions { - include_identity: false, - include_safety_preamble: false, - include_profile: false, - include_memory_md: true, - }, - ToolCallFormat::PFormat, - &[], - ); - - assert!( - !rendered.contains("background — not this conversation"), - "no MEMORY.md content → no dangling framing note in sub-agent path, got:\n{rendered}" - ); - - let _ = std::fs::remove_dir_all(workspace); -} +const PROFILE: &str = "# User Profile\nName: Jane Doe\nRole: Data scientist"; +const MEMORY: &str = "# Long-term memory\nUser prefers terse Rust answers."; #[test] -fn render_subagent_system_prompt_injects_profile_md_when_identity_included() { - // When identity is on, PROFILE.md must still be injected alongside - // SOUL/IDENTITY — the split must not regress the non-welcome path. - let workspace = std::env::temp_dir().join(format!( - "openhuman_prompt_profile_with_identity_{}", - uuid::Uuid::new_v4() - )); - std::fs::create_dir_all(&workspace).unwrap(); - std::fs::write(workspace.join("SOUL.md"), "# Soul\nctx").unwrap(); - std::fs::write(workspace.join("IDENTITY.md"), "# Identity\nctx").unwrap(); - std::fs::write(workspace.join("PROFILE.md"), "# User Profile\nhello").unwrap(); - - let tools: Vec> = vec![Box::new(TestTool)]; - let rendered = render_subagent_system_prompt( - &workspace, - "test-model", - &[0], - &tools, - &[], - "You are a specialist.", - SubagentRenderOptions { - include_identity: true, - include_safety_preamble: false, - include_profile: true, - include_memory_md: false, - }, - ToolCallFormat::PFormat, - &[], +fn subagent_profile_md_follows_include_profile_flag_independent_of_identity() { + // include_profile=true injects PROFILE.md even with the identity preamble + // omitted (SOUL/IDENTITY stay hidden); with identity on, all three appear. + let soul = [ + ("SOUL.md", "# Soul\nctx"), + ("IDENTITY.md", "# Identity\nctx"), + ("PROFILE.md", PROFILE), + ]; + let rendered = render_with_files(&soul, only(false, true, false)); + assert!(rendered.contains("### PROFILE.md"), "{rendered}"); + assert!(rendered.contains("Jane Doe"), "{rendered}"); + assert!(!rendered.contains("## Project Context"), "{rendered}"); + assert!( + !rendered.contains("### SOUL.md") && !rendered.contains("### IDENTITY.md"), + "{rendered}" ); - assert!(rendered.contains("## Project Context")); - assert!(rendered.contains("### SOUL.md")); - assert!(rendered.contains("### IDENTITY.md")); - assert!(rendered.contains("### PROFILE.md")); - assert!(rendered.contains("hello")); + let rendered = render_with_files(&soul, only(true, true, false)); + for header in [ + "## Project Context", + "### SOUL.md", + "### IDENTITY.md", + "### PROFILE.md", + ] { + assert!(rendered.contains(header), "{header}: {rendered}"); + } - let _ = std::fs::remove_dir_all(workspace); + // include_profile=false never leaks the file, even when it is on disk. + let rendered = render_with_files(&soul, SubagentRenderOptions::narrow()); + assert!(!rendered.contains("### PROFILE.md"), "{rendered}"); + assert!(!rendered.contains("ctx"), "{rendered}"); } #[test] fn render_subagent_system_prompt_silently_skips_missing_profile_md() { - // Pre-onboarding workspaces have no PROFILE.md. The renderer must - // not emit a noisy "[File not found: PROFILE.md]" placeholder or - // an orphan "### PROFILE.md" header — the subagent prompt stays - // focused on tools. - let workspace = std::env::temp_dir().join(format!( - "openhuman_prompt_profile_missing_{}", - uuid::Uuid::new_v4() - )); - std::fs::create_dir_all(&workspace).unwrap(); - - let tools: Vec> = vec![Box::new(TestTool)]; - let rendered = render_subagent_system_prompt( - &workspace, - "test-model", - &[0], - &tools, - &[], - "You are a specialist agent.", - SubagentRenderOptions::narrow(), - ToolCallFormat::PFormat, - &[], - ); - - assert!( - !rendered.contains("### PROFILE.md"), - "empty/missing PROFILE.md should not emit a header, got:\n{rendered}" - ); + // Pre-onboarding workspaces have no PROFILE.md: no orphan header, no + // "[File not found]" placeholder. + let rendered = render_with_files(&[], only(false, true, false)); + assert!(!rendered.contains("### PROFILE.md"), "{rendered}"); assert!( !rendered.contains("[File not found: PROFILE.md]"), - "missing PROFILE.md should be silent, not a noisy placeholder" + "{rendered}" ); - - let _ = std::fs::remove_dir_all(workspace); } #[test] -fn narrow_agent_with_omit_identity_still_loads_profile_md() { - // Verify that an agent configured with omit_identity=true/ - // omit_safety_preamble=true/omit_profile=false still gets PROFILE.md injected. - // This exercises the SubagentRenderOptions::from_definition_flags path for agents - // that want PROFILE.md without the full SOUL/IDENTITY preamble. - let workspace = std::env::temp_dir().join(format!( - "openhuman_prompt_narrow_agent_flags_{}", - uuid::Uuid::new_v4() - )); - std::fs::create_dir_all(&workspace).unwrap(); - std::fs::write( - workspace.join("PROFILE.md"), - "# User Profile\nTimezone: PST\nRole: Crypto trader", - ) - .unwrap(); - - let options = SubagentRenderOptions::from_definition_flags( - true, // omit_identity - true, // omit_safety_preamble - false, // omit_profile — opts IN to PROFILE.md - false, // omit_memory_md — opts IN to MEMORY.md too - ); - - let tools: Vec> = vec![Box::new(TestTool)]; - let rendered = render_subagent_system_prompt( - &workspace, - "test-model", - &[0], - &tools, - &[], - "# Specialist Agent\n\nYou are a specialist.", - options, - ToolCallFormat::PFormat, - &[], - ); - - assert!( - rendered.contains("### PROFILE.md"), - "agent with omit_profile=false must load PROFILE.md, got:\n{rendered}" - ); - assert!( - rendered.contains("Crypto trader"), - "PROFILE.md body must reach the agent prompt" - ); - - let _ = std::fs::remove_dir_all(workspace); +fn subagent_definition_flags_gate_profile_md() { + // omit_profile=false opts IN even with omit_identity=true. + let rendered = render_with_files( + &[("PROFILE.md", PROFILE)], + SubagentRenderOptions::from_definition_flags(true, true, false, false), + ); + assert!(rendered.contains("### PROFILE.md"), "{rendered}"); + assert!(rendered.contains("Jane Doe"), "{rendered}"); + + // A narrow specialist (every omit_* true) must not see it. + let rendered = render_with_files( + &[("PROFILE.md", PROFILE)], + SubagentRenderOptions::from_definition_flags(true, true, true, true), + ); + assert!(!rendered.contains("### PROFILE.md"), "{rendered}"); + assert!(!rendered.contains("Jane Doe"), "{rendered}"); } #[test] -fn narrow_subagent_definition_flags_skip_profile_md() { - // Inverse of `welcome_agent_definition_flags_still_load_profile_md`: - // a narrow specialist (e.g. `code_executor`, `critic`) leaves - // `omit_profile` at its default `true`. PROFILE.md must NOT be - // injected even when present on disk — the narrow runner is - // task-focused and should not pay the token cost. - let workspace = std::env::temp_dir().join(format!( - "openhuman_prompt_narrow_flags_{}", - uuid::Uuid::new_v4() - )); - std::fs::create_dir_all(&workspace).unwrap(); - std::fs::write( - workspace.join("PROFILE.md"), - "# User Profile\nTimezone: PST\nRole: Crypto trader", - ) - .unwrap(); - - // Mirrors e.g. `critic/agent.toml` — all omit_* default-true. - let options = SubagentRenderOptions::from_definition_flags(true, true, true, true); - - let tools: Vec> = vec![Box::new(TestTool)]; - let rendered = render_subagent_system_prompt( - &workspace, - "test-model", - &[0], - &tools, - &[], - "You are a narrow specialist.", - options, - ToolCallFormat::PFormat, - &[], +fn render_subagent_system_prompt_frames_memory_md_as_background() { + // GH-4745: sub-agent MEMORY.md must share the background-memory frame so a + // fresh thread does not read it as prior in-thread conversation. + let rendered = render_with_files( + &[( + "MEMORY.md", + "# Long-term memory\nReviewed `def f(x)` last week; user prefers terse notes.", + )], + only(false, false, true), ); - assert!( - !rendered.contains("### PROFILE.md"), - "narrow specialist (omit_profile=true) must NOT load PROFILE.md, got:\n{rendered}" + rendered.contains("### MEMORY.md") && rendered.contains("terse notes"), + "{rendered}" ); + let frame_at = rendered + .find("background — not this conversation") + .unwrap_or_else(|| panic!("missing background frame: {rendered}")); + let heading_at = rendered.find("### MEMORY.md").unwrap(); assert!( - !rendered.contains("Crypto trader"), - "narrow specialist must not leak PROFILE.md body" + frame_at < heading_at, + "frame must precede block: {rendered}" ); - - let _ = std::fs::remove_dir_all(workspace); } #[test] -fn render_subagent_system_prompt_injects_memory_md_when_enabled() { - // Opt-in agents with `omit_memory_md = false` must see MEMORY.md - // (archivist-curated long-term memory) in their rendered prompt. - let workspace = std::env::temp_dir().join(format!( - "openhuman_prompt_memory_on_{}", - uuid::Uuid::new_v4() - )); - std::fs::create_dir_all(&workspace).unwrap(); - std::fs::write( - workspace.join("MEMORY.md"), - "# Long-term memory\nUser prefers terse Rust answers.", - ) - .unwrap(); - - let tools: Vec> = vec![Box::new(TestTool)]; - let rendered = render_subagent_system_prompt( - &workspace, - "test-model", - &[0], - &tools, - &[], - "You are a specialist agent.", - SubagentRenderOptions { - include_identity: false, - include_safety_preamble: false, - include_profile: false, - include_memory_md: true, - }, - ToolCallFormat::PFormat, - &[], - ); - - assert!( - rendered.contains("### MEMORY.md"), - "MEMORY.md header must appear when include_memory_md=true, got:\n{rendered}" - ); +fn render_subagent_system_prompt_omits_memory_framing_when_no_memory_content() { + // include_memory_md=true but no MEMORY.md on disk: no dangling frame. + let rendered = render_with_files(&[], only(false, false, true)); assert!( - rendered.contains("terse Rust answers"), - "MEMORY.md body must be injected when include_memory_md=true" + !rendered.contains("background — not this conversation"), + "{rendered}" ); - - let _ = std::fs::remove_dir_all(workspace); } #[test] -fn render_subagent_system_prompt_skips_memory_md_when_disabled() { - // Narrow specialists with `omit_memory_md = true` (the default) - // must NOT see MEMORY.md even when it exists on disk. - let workspace = std::env::temp_dir().join(format!( - "openhuman_prompt_memory_off_{}", - uuid::Uuid::new_v4() - )); - std::fs::create_dir_all(&workspace).unwrap(); - std::fs::write( - workspace.join("MEMORY.md"), - "# Long-term memory\nUser prefers terse Rust answers.", - ) - .unwrap(); - - let tools: Vec> = vec![Box::new(TestTool)]; - let rendered = render_subagent_system_prompt( - &workspace, - "test-model", - &[0], - &tools, - &[], - "You are a narrow specialist.", - SubagentRenderOptions::narrow(), - ToolCallFormat::PFormat, - &[], - ); - - assert!( - !rendered.contains("### MEMORY.md"), - "MEMORY.md must NOT appear when include_memory_md=false, got:\n{rendered}" - ); - assert!( - !rendered.contains("terse Rust answers"), - "MEMORY.md body must not leak when include_memory_md=false" - ); - - let _ = std::fs::remove_dir_all(workspace); +fn subagent_memory_md_follows_include_memory_flag() { + let rendered = render_with_files(&[("MEMORY.md", MEMORY)], only(false, false, true)); + assert!(rendered.contains("### MEMORY.md"), "{rendered}"); + assert!(rendered.contains("terse Rust answers"), "{rendered}"); + + let rendered = render_with_files(&[("MEMORY.md", MEMORY)], SubagentRenderOptions::narrow()); + assert!(!rendered.contains("### MEMORY.md"), "{rendered}"); + assert!(!rendered.contains("terse Rust answers"), "{rendered}"); } #[test] diff --git a/crates/openhuman-core/src/agent/session_import/live_tests.rs b/crates/openhuman-core/src/agent/session_import/live_tests.rs index 23367af664a..0bbc419b3d8 100644 --- a/crates/openhuman-core/src/agent/session_import/live_tests.rs +++ b/crates/openhuman-core/src/agent/session_import/live_tests.rs @@ -11,7 +11,7 @@ use std::path::Path; use tempfile::TempDir; -use tinyagents_harness::store::{AppendStore, FileStore, JsonlAppendStore, Store}; +use tinyagents_harness::store::{AppendStore, JsonlAppendStore}; use super::live::{dual_write_enabled, shadow_reads_enabled}; use super::projector::journal_message_from_transcript as project; @@ -19,17 +19,13 @@ use crate::agent::messages::{ attach_chat_tool_failure_metadata, attach_chat_turn_usage_metadata, transcript_message_from_chat, ChatMessage, }; -use tinyagents_session::transcript::import::convert::{ - journal_messages as journal_messages_with, sanitize_store_name, stream_name, -}; +use tinyagents_session::transcript::import::convert::journal_messages as journal_messages_with; use tinyagents_session::transcript::import::live::{ shadow_read_compare as shadow_read_compare_with, write_live_turn as write_live_turn_with, ShadowReadOutcome, }; use tinyagents_session::transcript::import::ops::store_root; -use tinyagents_session::transcript::import::types::{ - JournalMessage, SessionDescriptor, NS_SESSIONS, -}; +use tinyagents_session::transcript::import::types::JournalMessage; use tinyagents_session::transcript::{ read_transcript, write_transcript, MessageUsage, SessionTranscript, TranscriptMeta, TranscriptToolCall, TurnUsage, @@ -138,78 +134,6 @@ async fn journal_readback(ws: &Path, stream: &str) -> Vec { .collect() } -#[tokio::test] -async fn live_dual_write_matches_legacy_jsonl_render() { - let ws = TempDir::new().expect("tempdir"); - let stem = "1719_orchestrator"; - let jsonl_path = ws.path().join("session_raw").join(format!("{stem}.jsonl")); - - // A user turn + an assistant turn. The base messages carry no usage - // metadata: the legacy writer embeds it from its `turn_usage` argument, - // exactly as `persist_session_transcript` does in production. - let base_messages = vec![ChatMessage::user("hi"), ChatMessage::assistant("done")]; - let meta = meta("t-root"); - let usage = turn_usage(); - - // (1) Legacy authoritative write — the primary persistence path. - write_transcript( - &jsonl_path, - &durable_messages(&base_messages), - &meta, - Some(&usage), - ) - .expect("legacy write"); - - // (2) Live dual-write mirrors the authoritative JSONL read-back. The - // round-trip adds replay provenance that is part of shadow-read parity. - let transcript = read_transcript(&jsonl_path).expect("read legacy transcript for mirror"); - write_live_turn(ws.path(), stem, &transcript) - .await - .expect("live dual-write"); - - // Parity: the store journal must equal the importer's read-back of the - // legacy JSONL, field for field (including reconstructed - // `openhuman_turn_usage` metadata and the tool-call id). - let expected = journal_messages(&read_transcript(&jsonl_path).expect("read legacy transcript")); - let actual = journal_readback(ws.path(), &stream_name(stem)).await; - assert_eq!( - actual, expected, - "live store stream diverges from the legacy JSONL render" - ); - - // The assistant record must carry the tool-call id via reconstructed usage. - let assistant = actual - .iter() - .find(|m| m.role == "assistant") - .expect("assistant record"); - let tool_id = assistant - .extra_metadata - .as_ref() - .and_then(|m| m.get("openhuman_turn_usage")) - .and_then(|u| u.get("tool_calls")) - .and_then(|t| t.get(0)) - .and_then(|c| c.get("id")) - .and_then(|id| id.as_str()); - assert_eq!(tool_id, Some("tc1"), "tool-call id lost on the store path"); - - // The session descriptor is upserted under the sanitized stem with the - // stem's thread id and journal stream, matching the importer's projection. - let kv = FileStore::new(store_root(ws.path()).join("kv")); - let desc_value = kv - .get(NS_SESSIONS, &sanitize_store_name(stem)) - .await - .expect("kv get") - .expect("descriptor present after live write"); - let desc: SessionDescriptor = serde_json::from_value(desc_value).expect("descriptor shape"); - assert_eq!(desc.session_key, stem); - assert_eq!(desc.thread_id, "t-root"); - assert!(!desc.thread_id_synthesized); - assert_eq!(desc.stream, stream_name(stem)); - assert_eq!(desc.dispatcher, "native"); - assert_eq!(desc.provider.as_deref(), Some("anthropic")); - assert_eq!(desc.model.as_deref(), Some("claude")); -} - /// The dual-write is driven by the `AgentConfig::session_dual_write` config /// flag (default ON) with the `OPENHUMAN_SESSION_DUAL_WRITE` env var as a pure /// kill switch. This exercises the decision matrix directly. Env mutation is @@ -363,54 +287,6 @@ async fn in_memory_store_reconstruction_diverges_from_legacy_on_sidecar_metadata ); } -/// When the store has no stream for the session (dual-write never ran), the -/// shadow read reports [`ShadowReadOutcome::Unavailable`] rather than a spurious -/// divergence, and a content mismatch is reported as -/// [`ShadowReadOutcome::Divergence`] with a compact first-diff index. -#[tokio::test] -async fn shadow_read_unavailable_and_divergence() { - let ws = TempDir::new().expect("tempdir"); - let stem = "1719_orchestrator"; - let meta = meta("t-root"); - - // No store write yet: empty/absent stream against a non-empty legacy - // transcript → Unavailable (no shadow), never a divergence. - let legacy = SessionTranscript { - tools: None, - meta: meta.clone(), - messages: durable_messages(&[ChatMessage::user("hi"), ChatMessage::assistant("done")]), - }; - assert_eq!( - shadow_read_compare(ws.path(), stem, &legacy).await, - ShadowReadOutcome::Unavailable, - "absent store stream must be reported as no shadow available" - ); - - // Now mirror the two-message transcript, then compare against a legacy - // transcript that has an extra trailing message: divergence at index 2. - write_live_turn(ws.path(), stem, &legacy) - .await - .expect("live dual-write"); - let diverging = SessionTranscript { - tools: None, - meta, - messages: durable_messages(&[ - ChatMessage::user("hi"), - ChatMessage::assistant("done"), - ChatMessage::user("more"), - ]), - }; - assert_eq!( - shadow_read_compare(ws.path(), stem, &diverging).await, - ShadowReadOutcome::Divergence { - legacy: 3, - shadow: 2, - first_diff: Some(2), - }, - "a trailing legacy-only message must be reported as a compact divergence" - ); -} - /// The shadow read is driven by the `AgentConfig::session_shadow_reads` config /// flag (default **ON** since the Phase 2 parity soak) with the /// `OPENHUMAN_SESSION_SHADOW_READS` env var as a @@ -471,85 +347,3 @@ fn shadow_read_flag_and_env_kill_switch() { // markdown transcripts `read_transcript_legacy_md` still parses. Both predate // the store, so both reach the shadow read by a different route than the happy // path above — and a real user upgrading has them on disk today. - -/// A resume off the legacy **date-grouped** layout (`session_raw/DDMMYYYY/`) -/// shadow-reads correctly. -/// -/// The session key is the file *stem*, so the enclosing directory must not -/// change it — a date-grouped transcript has to find the same store stream a -/// flat one would. If the key were ever derived from the path instead, every -/// pre-migration session would silently read as `Unavailable` and the parity -/// soak would look clean while covering nothing. -#[tokio::test] -async fn shadow_read_matches_across_the_legacy_date_grouped_layout() { - let ws = TempDir::new().expect("tempdir"); - let stem = "1719_orchestrator"; - // The legacy layout nests the transcript under a DDMMYYYY directory. - let dated_dir = ws.path().join("session_raw").join("01012024"); - std::fs::create_dir_all(&dated_dir).expect("create legacy dated dir"); - let jsonl_path = dated_dir.join(format!("{stem}.jsonl")); - - let base_messages = vec![ChatMessage::user("hi"), ChatMessage::assistant("done")]; - let meta = meta("t-root"); - let usage = turn_usage(); - - write_transcript( - &jsonl_path, - &durable_messages(&base_messages), - &meta, - Some(&usage), - ) - .expect("legacy write"); - - write_live_turn( - ws.path(), - stem, - &read_transcript(&jsonl_path).expect("read legacy dated transcript for mirror"), - ) - .await - .expect("live dual-write"); - - let legacy = read_transcript(&jsonl_path).expect("read legacy dated transcript"); - assert_eq!( - shadow_read_compare(ws.path(), stem, &legacy).await, - ShadowReadOutcome::Match { - messages: legacy.messages.len() - }, - "a date-grouped transcript must resolve the same store stream as a flat one" - ); -} - -/// A legacy **markdown** session shadow-reads as `Unavailable`, never as a -/// divergence. -/// -/// These transcripts predate the store entirely, so no dual-write ever ran for -/// them and no stream exists. That must read as "no shadow to compare", -/// because reporting it as divergence would flood the parity soak with false -/// positives from every old session on disk — and the whole point of the soak -/// is that a warning means something. -#[tokio::test] -async fn shadow_read_of_a_legacy_markdown_session_is_unavailable_not_divergent() { - let ws = TempDir::new().expect("tempdir"); - let stem = "1719_orchestrator"; - let md_path = ws.path().join("sessions").join("01012024"); - std::fs::create_dir_all(&md_path).expect("create legacy md dir"); - let md_file = md_path.join(format!("{stem}.md")); - - // The pre-JSONL on-disk shape: an HTML-comment header plus `` - // delimited bodies. - std::fs::write( - &md_file, - "\n\n\nhello\n\n\nhi back\n\n", - ) - .expect("write legacy md"); - - // `read_transcript` routes a `.md` path to the legacy parser. - let legacy = read_transcript(&md_file).expect("read legacy md transcript"); - assert_eq!(legacy.messages.len(), 2, "fixture parsed as two messages"); - - assert_eq!( - shadow_read_compare(ws.path(), stem, &legacy).await, - ShadowReadOutcome::Unavailable, - "a pre-store markdown session has no stream and must not read as divergence" - ); -} diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/mod.rs b/crates/openhuman-core/src/agent/subagent_host/ops/mod.rs index 551ecd7e31e..d0bd445c7d3 100644 --- a/crates/openhuman-core/src/agent/subagent_host/ops/mod.rs +++ b/crates/openhuman-core/src/agent/subagent_host/ops/mod.rs @@ -76,7 +76,3 @@ mod tests; #[cfg(test)] #[path = "../ops_dedup_tests.rs"] mod dedup_tests; - -#[cfg(test)] -#[path = "../ops_truncation_tests.rs"] -mod truncation_tests; diff --git a/crates/openhuman-core/src/agent/subagent_host/ops_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops_tests.rs index e061790ca1d..3a3c3fb0424 100644 --- a/crates/openhuman-core/src/agent/subagent_host/ops_tests.rs +++ b/crates/openhuman-core/src/agent/subagent_host/ops_tests.rs @@ -283,61 +283,7 @@ fn make_parent( } fn noop_memory() -> Arc { - struct NoopMemory; - #[async_trait] - impl crate::memory::Memory for NoopMemory { - async fn store( - &self, - _namespace: &str, - _key: &str, - _content: &str, - _category: crate::memory::MemoryCategory, - _session_id: Option<&str>, - ) -> anyhow::Result<()> { - Ok(()) - } - async fn recall( - &self, - _query: &str, - _limit: usize, - _opts: crate::memory::RecallOpts<'_>, - ) -> anyhow::Result> { - Ok(vec![]) - } - async fn get( - &self, - _namespace: &str, - _key: &str, - ) -> anyhow::Result> { - Ok(None) - } - async fn list( - &self, - _namespace: Option<&str>, - _category: Option<&crate::memory::MemoryCategory>, - _session_id: Option<&str>, - ) -> anyhow::Result> { - Ok(vec![]) - } - async fn forget(&self, _namespace: &str, _key: &str) -> anyhow::Result { - Ok(true) - } - async fn namespace_summaries( - &self, - ) -> anyhow::Result> { - Ok(vec![]) - } - async fn count(&self) -> anyhow::Result { - Ok(0) - } - async fn health_check(&self) -> bool { - true - } - fn name(&self) -> &str { - "noop" - } - } - Arc::new(NoopMemory) + crate::memory::test_support::noop_memory() } // ── Runtime spawn-hierarchy (tier) gate (issue #4098) ─────────────────────── diff --git a/crates/openhuman-core/src/agent/subagent_host/ops_tests_model_resolution_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops_tests_model_resolution_tests.rs index 6f815d977aa..45a89c181fa 100644 --- a/crates/openhuman-core/src/agent/subagent_host/ops_tests_model_resolution_tests.rs +++ b/crates/openhuman-core/src/agent/subagent_host/ops_tests_model_resolution_tests.rs @@ -241,9 +241,6 @@ async fn typed_mode_progress_emission_is_a_noop_without_sink() { assert_eq!(outcome.iterations, 1); } -// Truncation tests live in ops_truncation_tests.rs to keep this file -// under the ~500-line guideline. - // ── resolve_subagent_source ─────────────────────────────────────────── #[test] diff --git a/crates/openhuman-core/src/agent/subagent_host/ops_truncation_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops_truncation_tests.rs deleted file mode 100644 index e8141c07c7f..00000000000 --- a/crates/openhuman-core/src/agent/subagent_host/ops_truncation_tests.rs +++ /dev/null @@ -1,67 +0,0 @@ -/// Tests for the `max_result_chars` truncation logic in `ops.rs`. -/// -/// Kept in a dedicated file so `ops_tests.rs` stays under ~500 lines. -/// The logic under test lives in `run_subagent` — tests here cover the -/// char-safe truncation path directly without spinning up a provider. - -#[test] -fn max_result_chars_cap_is_enforced() { - // Verify that max_result_chars truncation uses char count (not bytes) - // and produces a truncated result ending with "[...truncated]". - let cap = 10usize; - let input = "hello world this is long".to_string(); - let original_chars = input.chars().count(); - let mut output = input.clone(); - if original_chars > cap { - let byte_offset = output - .char_indices() - .nth(cap) - .map(|(i, _)| i) - .unwrap_or(output.len()); - output.truncate(byte_offset); - output.push_str("\n[...truncated]"); - } - assert_eq!(&output[..10], "hello worl"); - assert!(output.ends_with("[...truncated]")); -} - -#[test] -fn max_result_chars_cap_is_char_safe_for_multibyte() { - // A cap landing in the middle of a multi-byte UTF-8 sequence must - // not panic. "café" has 4 chars but 'é' is 2 bytes — truncating at - // byte offset 4 with a raw String::truncate() would panic. - let cap = 3usize; // keep "caf", drop "é" - let input = "café latte".to_string(); - let original_chars = input.chars().count(); - let mut output = input.clone(); - if original_chars > cap { - let byte_offset = output - .char_indices() - .nth(cap) - .map(|(i, _)| i) - .unwrap_or(output.len()); - output.truncate(byte_offset); - output.push_str("\n[...truncated]"); - } - assert_eq!(output, "caf\n[...truncated]"); -} - -#[test] -fn max_result_chars_not_applied_when_none() { - let cap: Option = None; - let original = "short output".to_string(); - let mut output = original.clone(); - if let Some(c) = cap { - let char_len = output.chars().count(); - if char_len > c { - let byte_offset = output - .char_indices() - .nth(c) - .map(|(i, _)| i) - .unwrap_or(output.len()); - output.truncate(byte_offset); - output.push_str("\n[...truncated]"); - } - } - assert_eq!(output, original); -} diff --git a/crates/openhuman-core/src/agent/tinyagents/host/agent_memory_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/agent_memory_tests.rs index 327e7d553fb..21ccc04e83d 100644 --- a/crates/openhuman-core/src/agent/tinyagents/host/agent_memory_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/host/agent_memory_tests.rs @@ -594,17 +594,6 @@ async fn thread_summary_is_none_and_never_synthesized_from_recall() { .is_none()); } -#[tokio::test] -async fn usable_behind_a_trait_object() { - let (mem, _) = adapter(StubMemory::default()); - let boxed: Box = Box::new(mem); - boxed.remember(NewMemory::new("dyn safe")).await.unwrap(); - assert_eq!( - boxed.recall(RecallRequest::new("dyn")).await.unwrap().len(), - 1 - ); -} - #[test] fn a_blank_namespace_is_refused_rather_than_silently_widening_scope() { let (mem, _) = adapter(StubMemory::default()); diff --git a/crates/openhuman-core/src/agent/tinyagents/host/budget_gate_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/budget_gate_tests.rs index 0607fec4f35..03a22793974 100644 --- a/crates/openhuman-core/src/agent/tinyagents/host/budget_gate_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/host/budget_gate_tests.rs @@ -173,18 +173,3 @@ fn this_gate_never_asks_for_compression() { let gate = gate(AgentTokenjuiceCompression::Full); assert_eq!(gate.compression_hint(&crowded()), CompressionHint::None); } - -#[tokio::test] -async fn is_usable_as_a_trait_object() { - // Pins object safety: the harness stores this as `Arc`. - let gate: Arc = Arc::new(gate(AgentTokenjuiceCompression::Auto)); - let permit = gate - .acquire(&CallEstimate::new("m", 1, 1).with_agent("lead")) - .await - .expect("grants"); - drop(permit); - assert_eq!( - gate.compression_hint(&ContextState::default()), - CompressionHint::None - ); -} diff --git a/crates/openhuman-core/src/agent/tinyagents/host/context_composer_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/context_composer_tests.rs index 7b6fdb897df..bfbca12dec8 100644 --- a/crates/openhuman-core/src/agent/tinyagents/host/context_composer_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/host/context_composer_tests.rs @@ -157,14 +157,3 @@ fn the_model_name_falls_back_to_the_crate_default() { let pinned = OpenHumanContextComposer::new(config_in(dir.path())).with_model_name("haiku"); assert_eq!(pinned.model_name, "haiku"); } - -#[tokio::test] -async fn usable_as_a_trait_object() { - // Pins object safety — the harness stores this as - // `Arc`, so a non-dyn-safe impl would only fail - // at the wiring site, not here. - let dir = tempfile::tempdir().expect("tempdir"); - let composer: Arc = - Arc::new(OpenHumanContextComposer::new(config_in(dir.path()))); - assert!(composer.compose_system_prompt(&request()).await.is_ok()); -} diff --git a/crates/openhuman-core/src/agent/tinyagents/host/definition_registry_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/definition_registry_tests.rs index 2be8379bbbf..d2119e4073b 100644 --- a/crates/openhuman-core/src/agent/tinyagents/host/definition_registry_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/host/definition_registry_tests.rs @@ -457,16 +457,6 @@ async fn list_is_stable_across_calls() { assert_eq!(first, second); } -#[tokio::test] -async fn is_usable_as_a_trait_object() { - let registry: Box = Box::new(builtins()); - assert!(registry - .resolve("orchestrator") - .await - .expect("resolve") - .is_some()); -} - #[tokio::test] async fn an_empty_catalogue_misses_everything_without_erroring() { let registry = registry_of(Vec::new()); diff --git a/crates/openhuman-core/src/agent/tinyagents/host/progress_sink_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/progress_sink_tests.rs index dfe0036e2cb..9a8019006f2 100644 --- a/crates/openhuman-core/src/agent/tinyagents/host/progress_sink_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/host/progress_sink_tests.rs @@ -1,5 +1,4 @@ use super::*; -use std::sync::Arc; use tinyagents_harness::ids::{CallId, RunId, ThreadId}; use tinyinference_llm::usage::Usage; use tokio::sync::mpsc; @@ -488,14 +487,3 @@ async fn a_closed_channel_is_survivable() { .await; assert_eq!(sink.dropped(), 2); } - -#[tokio::test] -async fn works_through_an_arc_trait_object() { - let (tx, mut rx) = mpsc::channel(8); - let dynamic: Arc = Arc::new(OpenHumanProgressSink::new(tx)); - dynamic.emit(started()).await; - assert!(matches!( - rx.try_recv().expect("event forwarded"), - AgentProgress::TurnStarted - )); -} diff --git a/crates/openhuman-core/src/agent/tinyagents/host/steering.rs b/crates/openhuman-core/src/agent/tinyagents/host/steering.rs index 67b314ae22a..60921aadafe 100644 --- a/crates/openhuman-core/src/agent/tinyagents/host/steering.rs +++ b/crates/openhuman-core/src/agent/tinyagents/host/steering.rs @@ -4,11 +4,6 @@ use std::sync::OnceLock; use tinyagents_graph::orchestration::SteeringRegistry; #[cfg(test)] -use tinyagents_graph::{ - InMemoryTaskStore, OrchestrationTaskKind, OrchestrationTaskResult, OrchestrationTaskSpec, - OrchestrationTaskStatus, TaskStore, -}; -#[cfg(test)] use tinyagents_harness::ids::TaskId; use tinyagents_harness::steering::{SteeringCommandKind, SteeringHandle, SteeringPolicy}; diff --git a/crates/openhuman-core/src/agent/tinyagents/host/tool_outcome_classifier_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/tool_outcome_classifier_tests.rs index cc8efcba973..ddf9dbb7ee4 100644 --- a/crates/openhuman-core/src/agent/tinyagents/host/tool_outcome_classifier_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/host/tool_outcome_classifier_tests.rs @@ -312,13 +312,3 @@ fn the_dispatched_name_changes_the_verdict_only_for_timeouts() { "a timeout must distinguish an external-effect tool from a safe one" ); } - -#[test] -fn usable_as_a_trait_object() { - let classifier: std::sync::Arc = - std::sync::Arc::new(OpenHumanToolOutcomeClassifier::default()); - assert_eq!( - classifier.classify("shell", &result(Some("503"), "")), - OutcomeClass::RetryableFailure - ); -} diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rs index afad24af163..7afc3f639cf 100644 --- a/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rs @@ -217,31 +217,6 @@ async fn microcompact_clears_older_tool_bodies_and_keeps_recent() { assert_eq!(req.messages[3].text(), "thinking"); } -#[tokio::test] -async fn microcompact_is_a_noop_when_within_keep_recent() { - let mw = MicrocompactMiddleware::new(5, CLEARED_PLACEHOLDER); - let mut req = ModelRequest::new(vec![TaMessage::tool("t1", "A"), TaMessage::tool("t2", "B")]); - mw.before_model(&mut ctx(), &(), &mut req).await.unwrap(); - assert_eq!(req.messages[0].text(), "A"); - assert_eq!(req.messages[1].text(), "B"); -} - -#[tokio::test] -async fn microcompact_is_idempotent() { - let mw = MicrocompactMiddleware::new(1, CLEARED_PLACEHOLDER); - let mut req = ModelRequest::new(vec![ - TaMessage::tool("t1", "FIRST"), - TaMessage::tool("t2", "SECOND"), - ]); - mw.before_model(&mut ctx(), &(), &mut req).await.unwrap(); - let after_first = req.messages[0].text(); - assert_eq!(after_first, CLEARED_PLACEHOLDER); - // Second pass leaves the already-cleared body as the placeholder. - mw.before_model(&mut ctx(), &(), &mut req).await.unwrap(); - assert_eq!(req.messages[0].text(), CLEARED_PLACEHOLDER); - assert_eq!(req.messages[1].text(), "SECOND"); -} - // ── ToolOutputMiddleware ──────────────────────────────────────────────── #[tokio::test] diff --git a/crates/openhuman-core/src/agent/tinyagents/orchestration_tests.rs b/crates/openhuman-core/src/agent/tinyagents/orchestration_tests.rs index c3f524e22e5..240762a7d43 100644 --- a/crates/openhuman-core/src/agent/tinyagents/orchestration_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/orchestration_tests.rs @@ -1,30 +1,5 @@ use super::*; -#[tokio::test] -async fn task_store_tracks_lifecycle() { - // Smoke the re-exported orchestration primitives: a task moves - // Pending → Running → Completed and is readable back by id. - let store = InMemoryTaskStore::new(); - let spec = OrchestrationTaskSpec::new( - "task-1", - OrchestrationTaskKind::SubAgent { - agent: "researcher".to_string(), - }, - ); - let rec = store.insert(spec).expect("insert"); - assert_eq!(rec.status, OrchestrationTaskStatus::Pending); - - store.mark_running(rec.task_id()).expect("running"); - let done = store - .complete(rec.task_id(), OrchestrationTaskResult::text("done")) - .expect("complete"); - assert_eq!(done.status, OrchestrationTaskStatus::Completed); - assert_eq!( - store.get(rec.task_id()).map(|r| r.status), - Some(OrchestrationTaskStatus::Completed) - ); -} - #[test] fn steering_registry_reexport_registers_task_handles() { let registry = shared_steering_registry(); diff --git a/crates/openhuman-core/src/agent/tinyagents/topology_tests.rs b/crates/openhuman-core/src/agent/tinyagents/topology_tests.rs index ee303363d86..9fc67c80824 100644 --- a/crates/openhuman-core/src/agent/tinyagents/topology_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/topology_tests.rs @@ -1,26 +1,13 @@ use super::*; #[test] -fn all_topologies_includes_the_member_graph() { +fn all_topologies_includes_member_delegation_and_workflow_scheduler() { let reports = all_graph_topologies(); - let member = reports - .iter() - .find(|r| r.name == "agent_teams:member") - .expect("the agent_teams member graph should be exported"); - - // The member graph is a fixed, well-formed structure. - assert!( - member.ok, - "member graph should validate structurally: {:?}", - member.errors - ); - assert!(member.errors.is_empty()); -} - -#[test] -fn all_topologies_includes_delegation_and_workflow_scheduler() { - let reports = all_graph_topologies(); - for name in ["delegation", "workflow_runs:scheduler_preview"] { + for name in [ + "agent_teams:member", + "delegation", + "workflow_runs:scheduler_preview", + ] { let report = reports .iter() .find(|r| r.name == name) @@ -85,39 +72,3 @@ fn all_topologies_names_do_not_collide_with_production_tools() { ); } } - -#[test] -fn delegation_topology_names_the_revision_loop_nodes() { - let t = tinyagents_graph::delegation::delegation_graph_topology().expect("builds"); - let names: Vec<&str> = t.nodes.iter().map(|n| n.id.as_str()).collect(); - for expected in ["plan", "execute", "review", "finalize"] { - assert!( - names.contains(&expected), - "missing node {expected}: {names:?}" - ); - } -} - -#[test] -fn member_report_renders_mermaid_and_valid_json() { - let t = - tinyagents_orchestration::teams::member_graph_topology().expect("member topology builds"); - let report = describe("agent_teams:member", &t); - - // Mermaid is a flowchart with at least the entry node rendered. - assert!( - report.mermaid.contains("flowchart"), - "mermaid should be a flowchart: {}", - report.mermaid - ); - assert!(!t.nodes.is_empty(), "the graph should declare nodes"); - - // JSON round-trips to a value carrying the same node set. - let parsed: serde_json::Value = - serde_json::from_str(&report.json).expect("topology JSON parses"); - assert!( - parsed.get("nodes").is_some(), - "serialized topology should carry its nodes: {}", - report.json - ); -} diff --git a/crates/openhuman-core/src/agent/tinyagents/use_skill_dispatch_tests.rs b/crates/openhuman-core/src/agent/tinyagents/use_skill_dispatch_tests.rs index 01ee5a32af2..594636e060b 100644 --- a/crates/openhuman-core/src/agent/tinyagents/use_skill_dispatch_tests.rs +++ b/crates/openhuman-core/src/agent/tinyagents/use_skill_dispatch_tests.rs @@ -18,7 +18,7 @@ use crate::agent::harness::definition::AgentDefinitionRegistry; use crate::agent::harness::ParentExecutionContext; use crate::agent::prompts::ToolCallFormat; use crate::agent::tinyagents::tools::CanonicalSharedToolAdapter; -use crate::memory::{Memory, MemoryCategory, MemoryEntry, NamespaceSummary, RecallOpts}; +use crate::memory::test_support::NoopMemory; use async_trait::async_trait; use serde_json::json; use std::path::Path; @@ -82,64 +82,6 @@ impl ChatModel<()> for AnyAnswerModel { #[allow(dead_code)] fn unused_message_ref(_m: &Message) {} -struct NoopMemory; - -#[async_trait] -impl Memory for NoopMemory { - async fn store( - &self, - _namespace: &str, - _key: &str, - _value: &str, - _category: MemoryCategory, - _source: Option<&str>, - ) -> anyhow::Result<()> { - Ok(()) - } - - async fn recall( - &self, - _query: &str, - _limit: usize, - _opts: RecallOpts<'_>, - ) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn get(&self, _namespace: &str, _key: &str) -> anyhow::Result> { - Ok(None) - } - - async fn list( - &self, - _namespace: Option<&str>, - _category: Option<&MemoryCategory>, - _source: Option<&str>, - ) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn forget(&self, _namespace: &str, _key: &str) -> anyhow::Result { - Ok(false) - } - - async fn namespace_summaries(&self) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn count(&self) -> anyhow::Result { - Ok(0) - } - - async fn health_check(&self) -> bool { - true - } - - fn name(&self) -> &str { - "noop" - } -} - fn parent_execution_context(workspace_dir: &Path) -> ParentExecutionContext { ParentExecutionContext { workspace_descriptor: None, diff --git a/crates/openhuman-core/src/agent/tools/delegate_tests.rs b/crates/openhuman-core/src/agent/tools/delegate_tests.rs index 9c21f35b509..6bbf5e9267e 100644 --- a/crates/openhuman-core/src/agent/tools/delegate_tests.rs +++ b/crates/openhuman-core/src/agent/tools/delegate_tests.rs @@ -61,17 +61,10 @@ fn schema_lists_agent_names() { } #[tokio::test] -async fn missing_agent_param() { +async fn missing_required_params_are_rejected() { let tool = DelegateTool::new(sample_agents(), test_security()); - let result = tool.execute(json!({"prompt": "test"})).await; - assert!(result.is_err()); -} - -#[tokio::test] -async fn missing_prompt_param() { - let tool = DelegateTool::new(sample_agents(), test_security()); - let result = tool.execute(json!({"agent": "researcher"})).await; - assert!(result.is_err()); + assert!(tool.execute(json!({"prompt": "test"})).await.is_err()); + assert!(tool.execute(json!({"agent": "researcher"})).await.is_err()); } #[tokio::test] @@ -87,25 +80,16 @@ async fn unknown_agent_returns_error() { #[tokio::test] async fn depth_limit_enforced() { - let tool = DelegateTool::with_depth(sample_agents(), test_security(), 3); - let result = tool - .execute(json!({"agent": "researcher", "prompt": "test"})) - .await - .unwrap(); - assert!(result.is_error); - assert!(result.output().contains("depth limit")); -} - -#[tokio::test] -async fn depth_limit_per_agent() { - // coder has max_depth=2, so depth=2 should be blocked - let tool = DelegateTool::with_depth(sample_agents(), test_security(), 2); - let result = tool - .execute(json!({"agent": "coder", "prompt": "test"})) - .await - .unwrap(); - assert!(result.is_error); - assert!(result.output().contains("depth limit")); + // Global limit, then coder's own max_depth=2 blocking at depth 2. + for (agent, depth) in [("researcher", 3), ("coder", 2)] { + let tool = DelegateTool::with_depth(sample_agents(), test_security(), depth); + let result = tool + .execute(json!({"agent": agent, "prompt": "test"})) + .await + .unwrap(); + assert!(result.is_error, "{agent}@{depth}"); + assert!(result.output().contains("depth limit"), "{agent}@{depth}"); + } } #[test] @@ -119,25 +103,16 @@ fn empty_agents_schema() { } #[tokio::test] -async fn blank_agent_rejected() { - let tool = DelegateTool::new(sample_agents(), test_security()); - let result = tool - .execute(json!({"agent": " ", "prompt": "test"})) - .await - .unwrap(); - assert!(result.is_error); - assert!(result.output().contains("must not be empty")); -} - -#[tokio::test] -async fn blank_prompt_rejected() { +async fn blank_agent_or_prompt_rejected() { let tool = DelegateTool::new(sample_agents(), test_security()); - let result = tool - .execute(json!({"agent": "researcher", "prompt": " \t "})) - .await - .unwrap(); - assert!(result.is_error); - assert!(result.output().contains("must not be empty")); + for args in [ + json!({"agent": " ", "prompt": "test"}), + json!({"agent": "researcher", "prompt": " \t "}), + ] { + let result = tool.execute(args.clone()).await.unwrap(); + assert!(result.is_error, "{args}"); + assert!(result.output().contains("must not be empty"), "{args}"); + } } #[tokio::test] diff --git a/crates/openhuman-core/src/agent/tools/remember_preference_tests.rs b/crates/openhuman-core/src/agent/tools/remember_preference_tests.rs index dde1202405a..1c6a8aedab7 100644 --- a/crates/openhuman-core/src/agent/tools/remember_preference_tests.rs +++ b/crates/openhuman-core/src/agent/tools/remember_preference_tests.rs @@ -119,79 +119,34 @@ fn schema_has_required_fields() { #[tokio::test] #[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \ the tool resolves the bound driver rather than being handed a memory handle"] -async fn missing_class_returns_error() { +async fn invalid_arguments_return_a_tool_error_naming_the_problem() { + let cases = [ + (json!({"key": "timezone", "value": "IST"}), "class"), + ( + json!({"class": "bogus", "key": "timezone", "value": "IST"}), + "invalid class", + ), + (json!({"class": "style", "value": "terse"}), "key"), + ( + json!({"class": "style", "key": " ", "value": "terse"}), + "key cannot be empty", + ), + ( + json!({"class": "style", "key": "my pref", "value": "terse"}), + "invalid characters", + ), + (json!({"class": "tooling", "key": "pkg_mgr"}), "value"), + ]; let tool = RememberPreferenceTool::new(test_security()); - let result = tool - .execute(json!({"key": "timezone", "value": "IST"})) - .await - .unwrap(); - assert!(result.is_error); - assert!(result.output().contains("class")); -} - -#[tokio::test] -#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \ -the tool resolves the bound driver rather than being handed a memory handle"] -async fn invalid_class_returns_error() { - let tool = RememberPreferenceTool::new(test_security()); - let result = tool - .execute(json!({"class": "bogus", "key": "timezone", "value": "IST"})) - .await - .unwrap(); - assert!(result.is_error); - assert!(result.output().contains("invalid class")); -} - -#[tokio::test] -#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \ -the tool resolves the bound driver rather than being handed a memory handle"] -async fn missing_key_returns_error() { - let tool = RememberPreferenceTool::new(test_security()); - let result = tool - .execute(json!({"class": "style", "value": "terse"})) - .await - .unwrap(); - assert!(result.is_error); - assert!(result.output().contains("key")); -} - -#[tokio::test] -#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \ -the tool resolves the bound driver rather than being handed a memory handle"] -async fn empty_key_returns_error() { - let tool = RememberPreferenceTool::new(test_security()); - let result = tool - .execute(json!({"class": "style", "key": " ", "value": "terse"})) - .await - .unwrap(); - assert!(result.is_error); - assert!(result.output().contains("key cannot be empty")); -} - -#[tokio::test] -#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \ -the tool resolves the bound driver rather than being handed a memory handle"] -async fn key_with_spaces_returns_error() { - let tool = RememberPreferenceTool::new(test_security()); - let result = tool - .execute(json!({"class": "style", "key": "my pref", "value": "terse"})) - .await - .unwrap(); - assert!(result.is_error); - assert!(result.output().contains("invalid characters")); -} - -#[tokio::test] -#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \ -the tool resolves the bound driver rather than being handed a memory handle"] -async fn missing_value_returns_error() { - let tool = RememberPreferenceTool::new(test_security()); - let result = tool - .execute(json!({"class": "tooling", "key": "pkg_mgr"})) - .await - .unwrap(); - assert!(result.is_error); - assert!(result.output().contains("value")); + for (args, expected) in cases { + let result = tool.execute(args.clone()).await.unwrap(); + assert!(result.is_error, "{args}"); + assert!( + result.output().contains(expected), + "{args}: {}", + result.output() + ); + } } // ── Successful upsert ─────────────────────────────────────────────────── diff --git a/crates/openhuman-core/src/backend/client_tests.rs b/crates/openhuman-core/src/backend/client_tests.rs index 29cb42bbe5d..7410065707a 100644 --- a/crates/openhuman-core/src/backend/client_tests.rs +++ b/crates/openhuman-core/src/backend/client_tests.rs @@ -144,59 +144,22 @@ async fn authed_json_sends_a_session_credential_as_a_bearer_only() { assert!(request_headers.get("x-api-key").is_none()); } -#[tokio::test] -async fn authed_json_sends_bearer_and_host_headers() { - let (base_url, captured) = spawn_header_capture_server().await; - let client = BackendClient::new(&base_url).unwrap(); - - let response = client - .authed_json("sdk-cutover-token", Method::GET, "/probe", None) - .await - .unwrap(); - assert_eq!(response, json!({ "ok": true })); - - let headers = captured.take(); - let request_headers = headers.last().unwrap(); - assert_eq!( - request_headers - .get("authorization") - .and_then(|value| value.to_str().ok()), - Some("Bearer sdk-cutover-token") - ); - assert!(request_headers.get(PRODUCT_IDENTITY_HEADER).is_some()); -} - // Regression: OPENHUMAN-TAURI-8K / Sentry issue 7473650958. // When config.api_url is a full LLM completions URL (e.g. /v1/chat/completions), // Url::join used to produce wrong paths like /v1/chat/teams/me/usage instead of // /teams/me/usage — BackendClient::new must strip the path to prevent this. #[test] fn new_strips_path_from_completions_url() { - let client = BackendClient::new("https://api.tinyhumans.ai/v1/chat/completions").unwrap(); - let url = client.url_for("/teams/me/usage").unwrap(); - assert_eq!(url.path(), "/teams/me/usage"); -} - -#[test] -fn new_strips_path_from_openai_style_url() { - let client = BackendClient::new("https://api.openai.com/v1/chat/completions").unwrap(); - let url = client.url_for("/teams/me/usage").unwrap(); - assert_eq!(url.path(), "/teams/me/usage"); - assert_eq!(url.host_str(), Some("api.openai.com")); -} - -#[test] -fn new_works_with_bare_origin() { - let client = BackendClient::new("https://api.tinyhumans.ai").unwrap(); - let url = client.url_for("/teams/me/usage").unwrap(); - assert_eq!(url.path(), "/teams/me/usage"); -} - -#[test] -fn new_works_with_trailing_slash() { - let client = BackendClient::new("https://api.tinyhumans.ai/").unwrap(); - let url = client.url_for("/teams/me/usage").unwrap(); - assert_eq!(url.path(), "/teams/me/usage"); + for base in [ + "https://api.tinyhumans.ai/v1/chat/completions", + "https://api.openai.com/v1/chat/completions", + "https://api.tinyhumans.ai", + "https://api.tinyhumans.ai/", + ] { + let client = BackendClient::new(base).unwrap(); + let url = client.url_for("/teams/me/usage").unwrap(); + assert_eq!(url.path(), "/teams/me/usage", "{base}"); + } } #[tokio::test] diff --git a/crates/openhuman-core/src/channels/bus_inbound_thread_id_tests_tests.rs b/crates/openhuman-core/src/channels/bus_inbound_thread_id_tests_tests.rs index ffc555651da..f71f9a2de17 100644 --- a/crates/openhuman-core/src/channels/bus_inbound_thread_id_tests_tests.rs +++ b/crates/openhuman-core/src/channels/bus_inbound_thread_id_tests_tests.rs @@ -1,5 +1,4 @@ use super::delivery::channel_message_body_with_idempotency; -use super::thread_id::{derive_inbound_client_id, derive_inbound_thread_id}; use serde_json::json; #[test] @@ -31,111 +30,3 @@ fn channel_message_body_preserves_caller_idempotency_key() { assert_eq!(body["idempotencyKey"], "caller-key"); } - -#[test] -fn socket_inbound_client_id_keys_per_sender() { - // Distinct senders in the same shared channel must produce distinct - // client_id labels so downstream consumers that key on client_id - // (audit log, future session caches) stay segregated. The - // thread_id is already per-sender; this is the matching client_id - // half of the pair. - let alice = derive_inbound_client_id("discord", Some("alice")); - let bob = derive_inbound_client_id("discord", Some("bob")); - assert_ne!(alice, bob, "co-channel senders must not collapse"); - assert!(alice.starts_with("inbound")); - assert!(bob.starts_with("inbound")); -} - -#[test] -fn socket_inbound_client_id_legacy_fallback_keeps_bare_inbound() { - // Legacy publishers that don't fill `sender` keep the historical - // `"inbound"` literal so single-DM flows (where there's no - // co-channel surface) are unchanged. - assert_eq!(derive_inbound_client_id("discord", None), "inbound"); - assert_eq!(derive_inbound_client_id("discord", Some("")), "inbound"); - assert_eq!(derive_inbound_client_id("discord", Some(" ")), "inbound"); -} - -#[test] -fn socket_inbound_keys_per_sender_combined_with_thread_id() { - // Regression: in a shared Discord channel, two distinct senders - // sending into the same channel/reply_target produce a fully - // distinct (client_id, thread_id) pair. This is the surface the - // wallet preparer-binding and parked-approval routing both rely - // on for per-user isolation. - let alice_thread = derive_inbound_thread_id("discord", Some("alice"), Some("#general"), None); - let bob_thread = derive_inbound_thread_id("discord", Some("bob"), Some("#general"), None); - let alice_client = derive_inbound_client_id("discord", Some("alice")); - let bob_client = derive_inbound_client_id("discord", Some("bob")); - - assert_ne!(alice_thread, bob_thread); - assert_ne!(alice_client, bob_client); - assert_ne!( - (alice_client.as_str(), alice_thread.as_str()), - (bob_client.as_str(), bob_thread.as_str()), - ); -} - -#[test] -fn legacy_channel_only_keeps_old_shape() { - // Publishers that don't pass sender must still produce a stable - // key so existing single-DM flows are unchanged. - assert_eq!( - derive_inbound_thread_id("telegram", None, None, None), - "channel:telegram" - ); -} - -#[test] -fn distinct_senders_get_distinct_keys() { - let a = derive_inbound_thread_id("discord", Some("alice"), Some("#general"), None); - let b = derive_inbound_thread_id("discord", Some("bob"), Some("#general"), None); - assert_ne!(a, b, "two senders in same channel must not collapse"); -} - -#[test] -fn slack_thread_anchor_splits_subthreads() { - let parent = derive_inbound_thread_id("slack", Some("u1"), Some("C1"), None); - let thread = derive_inbound_thread_id("slack", Some("u1"), Some("C1"), Some("1700.001")); - assert_ne!(parent, thread); -} - -#[test] -fn telegram_ignores_thread_ts() { - // Telegram uses thread_ts for transport routing only; memory key - // must stay stable across thread_ts updates inside the same DM. - let a = derive_inbound_thread_id("telegram", Some("u1"), Some("c1"), Some("100")); - let b = derive_inbound_thread_id("telegram", Some("u1"), Some("c1"), Some("200")); - assert_eq!(a, b); -} - -#[test] -fn telegram_chat_id_shape_still_ignores_thread_ts() { - // Regression: in production the socket layer addresses Telegram - // with raw chat ids like `tg:123` and `telegram:123` (matching - // the `:message` event name shape). The thread_ts - // carve-out must recognise both, not only the literal slug. - for channel in ["tg:123", "telegram:123", "tg", "telegram"] { - let a = derive_inbound_thread_id(channel, Some("u1"), Some("c1"), Some("100")); - let b = derive_inbound_thread_id(channel, Some("u1"), Some("c1"), Some("200")); - assert_eq!( - a, b, - "channel '{channel}' should ignore thread_ts (telegram provider)" - ); - } -} - -#[test] -fn non_telegram_channel_id_shape_still_splits_on_thread_ts() { - // Inverse: a `slack:` style channel must continue to - // honour thread_ts so Slack subthreads stay distinct. - let a = derive_inbound_thread_id("slack:T1", Some("u1"), Some("c1"), Some("100")); - let b = derive_inbound_thread_id("slack:T1", Some("u1"), Some("c1"), Some("200")); - assert_ne!(a, b); -} - -#[test] -fn empty_optional_fields_are_skipped() { - let only_sender = derive_inbound_thread_id("discord", Some("alice"), Some(" "), None); - assert_eq!(only_sender, "channel:discord/alice"); -} diff --git a/crates/openhuman-core/src/channels/runtime/dispatch_tests.rs b/crates/openhuman-core/src/channels/runtime/dispatch_tests.rs index 1a6b3491664..5cbe84297f1 100644 --- a/crates/openhuman-core/src/channels/runtime/dispatch_tests.rs +++ b/crates/openhuman-core/src/channels/runtime/dispatch_tests.rs @@ -66,24 +66,14 @@ fn ack_reaction_default_category() { } #[test] -fn ack_reaction_is_deterministic() { +fn ack_reaction_is_deterministic_and_total_on_edge_inputs() { let a = select_acknowledgment_reaction("thanks"); let b = select_acknowledgment_reaction("thanks"); assert_eq!(a, b, "same input should always yield same reaction"); -} - -#[test] -fn ack_reaction_handles_empty_input_without_panic() { - // `content.chars().next()` is None on empty input — must not panic. - let r = select_acknowledgment_reaction(""); - assert!(!r.is_empty()); -} - -#[test] -fn ack_reaction_handles_single_char() { - let r = select_acknowledgment_reaction("?"); - // Single "?" falls into question category (contains '?'). - assert!(is_in(r, &["🤔", "✍️"])); + // Empty input must not panic (`content.chars().next()` is None). + assert!(!select_acknowledgment_reaction("").is_empty()); + // A single "?" falls into the question category. + assert!(is_in(select_acknowledgment_reaction("?"), &["🤔", "✍️"])); } // ── build_channel_context_block (#928) ─────────────────────── diff --git a/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs b/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs index a007f5c0571..e7e3276249a 100644 --- a/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs +++ b/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs @@ -98,6 +98,10 @@ async fn start_channels_inner(mut config: Config) -> Result<()> { // is intentionally cheap and the loop body no-ops when there are // no connections. crate::integrations::composio::start_periodic_sync(); + // The folder, GitHub, RSS and web sources a driver without a source + // pipeline of its own (hosted memory) needs refreshed; each tick checks the + // driver bound at that moment. + crate::memory::sources::start_hosted_periodic_sync(); // Task-sources: subscribe to Composio connection-created events for // one-shot fetches, and spawn the periodic poll that pulls work from // configured external sources onto the agent's todo board. diff --git a/crates/openhuman-core/src/channels/runtime/startup_tests.rs b/crates/openhuman-core/src/channels/runtime/startup_tests.rs index ffe0d1ffa35..e1b26585080 100644 --- a/crates/openhuman-core/src/channels/runtime/startup_tests.rs +++ b/crates/openhuman-core/src/channels/runtime/startup_tests.rs @@ -18,99 +18,43 @@ fn config_with_chat_provider(s: Option<&str>) -> Config { } #[test] -fn chat_provider_unset_resolves_to_cloud() { - let config = config_with_chat_provider(None); - assert!(matches!( - resolve_chat_workload(&config), - ChatWorkloadResolution::Cloud - )); -} - -#[test] -fn chat_provider_blank_resolves_to_cloud() { - let config = config_with_chat_provider(Some("")); - assert!(matches!( - resolve_chat_workload(&config), - ChatWorkloadResolution::Cloud - )); -} - -#[test] -fn chat_provider_cloud_sentinel_resolves_to_cloud() { - let config = config_with_chat_provider(Some("cloud")); - assert!(matches!( - resolve_chat_workload(&config), - ChatWorkloadResolution::Cloud - )); -} - -#[test] -fn chat_provider_openhuman_sentinel_resolves_to_cloud() { - let config = config_with_chat_provider(Some("openhuman")); - assert!(matches!( - resolve_chat_workload(&config), - ChatWorkloadResolution::Cloud - )); -} - -#[test] -fn chat_provider_ollama_resolves_to_workload() { - let config = config_with_chat_provider(Some("ollama:llama3.2")); - match resolve_chat_workload(&config) { - ChatWorkloadResolution::Workload { - provider_string, - slug, - } => { - assert_eq!(provider_string, "ollama:llama3.2"); - assert_eq!(slug, "ollama"); - } - ChatWorkloadResolution::Cloud => panic!("expected Workload for ollama, got Cloud"), - } -} - -#[test] -fn chat_provider_lmstudio_resolves_to_workload() { - let config = config_with_chat_provider(Some("lmstudio:qwen2.5:0.5b")); - match resolve_chat_workload(&config) { - ChatWorkloadResolution::Workload { - provider_string, - slug, - } => { - assert_eq!(provider_string, "lmstudio:qwen2.5:0.5b"); - assert_eq!(slug, "lmstudio"); - } - ChatWorkloadResolution::Cloud => panic!("expected Workload for lmstudio"), - } -} - -#[test] -fn chat_provider_byok_slug_resolves_to_workload() { - let config = config_with_chat_provider(Some("openai:gpt-4o")); - match resolve_chat_workload(&config) { - ChatWorkloadResolution::Workload { - provider_string, - slug, - } => { - assert_eq!(provider_string, "openai:gpt-4o"); - assert_eq!(slug, "openai"); - } - ChatWorkloadResolution::Cloud => panic!("expected Workload for byok slug"), +fn chat_provider_unset_blank_or_sentinel_resolves_to_cloud() { + for value in [None, Some(""), Some("cloud"), Some("openhuman")] { + let config = config_with_chat_provider(value); + assert!( + matches!( + resolve_chat_workload(&config), + ChatWorkloadResolution::Cloud + ), + "{value:?} must resolve to cloud" + ); } } #[test] -fn chat_provider_claude_agent_sdk_resolves_to_workload() { - // Bare sentinel (no colon) — slug is the full string. - let config = config_with_chat_provider(Some("claude_agent_sdk")); - match resolve_chat_workload(&config) { - ChatWorkloadResolution::Workload { - provider_string, - slug, - } => { - assert_eq!(provider_string, "claude_agent_sdk"); - assert_eq!(slug, "claude_agent_sdk"); +fn chat_provider_local_and_byok_strings_resolve_to_workload() { + // (configured string, expected slug). The bare `claude_agent_sdk` + // sentinel has no colon, so its slug is the full string. + let cases = [ + ("ollama:llama3.2", "ollama"), + ("lmstudio:qwen2.5:0.5b", "lmstudio"), + ("openai:gpt-4o", "openai"), + ("claude_agent_sdk", "claude_agent_sdk"), + ]; + for (configured, expected_slug) in cases { + let config = config_with_chat_provider(Some(configured)); + match resolve_chat_workload(&config) { + ChatWorkloadResolution::Workload { + provider_string, + slug, + } => { + assert_eq!(provider_string, configured); + assert_eq!(slug, expected_slug); + } + ChatWorkloadResolution::Cloud => { + panic!("expected Workload for {configured}, got Cloud") + } } - ChatWorkloadResolution::Cloud => panic!("expected Workload for claude_agent_sdk"), } } diff --git a/crates/openhuman-core/src/channels/tests/context.rs b/crates/openhuman-core/src/channels/tests/context.rs deleted file mode 100644 index 66e7fdec58a..00000000000 --- a/crates/openhuman-core/src/channels/tests/context.rs +++ /dev/null @@ -1,159 +0,0 @@ -use super::super::context::{ - compact_sender_history, conversation_history_key, effective_channel_message_timeout_secs, - is_context_window_overflow_error, should_skip_memory_context_entry, ChannelRuntimeContext, - CHANNEL_HISTORY_COMPACT_CONTENT_CHARS, CHANNEL_HISTORY_COMPACT_KEEP_MESSAGES, - CHANNEL_MESSAGE_TIMEOUT_SECS, MIN_CHANNEL_MESSAGE_TIMEOUT_SECS, -}; -use super::super::traits; -use super::common::DummyModel; -use crate::agent::messages::ChatMessage; -use std::collections::HashMap; -use std::sync::{Arc, Mutex}; - -#[test] -fn effective_channel_message_timeout_secs_clamps_to_minimum() { - assert_eq!( - effective_channel_message_timeout_secs(0), - MIN_CHANNEL_MESSAGE_TIMEOUT_SECS - ); - assert_eq!( - effective_channel_message_timeout_secs(15), - MIN_CHANNEL_MESSAGE_TIMEOUT_SECS - ); - assert_eq!(effective_channel_message_timeout_secs(300), 300); -} - -#[test] -fn context_window_overflow_error_detector_matches_known_messages() { - let overflow_err = anyhow::anyhow!( - "OpenAI Codex stream error: Your input exceeds the context window of this model." - ); - assert!(is_context_window_overflow_error(&overflow_err)); - - let other_err = anyhow::anyhow!("OpenAI Codex API error (502 Bad Gateway): error code: 502"); - assert!(!is_context_window_overflow_error(&other_err)); -} - -#[test] -fn memory_context_skip_rules_exclude_history_blobs() { - assert!(should_skip_memory_context_entry( - "telegram_123_history", - r#"[{"role":"user"}]"# - )); - assert!(!should_skip_memory_context_entry("telegram_123_45", "hi")); -} - -#[test] -fn compact_sender_history_keeps_recent_truncated_messages() { - let mut histories = HashMap::new(); - let sender = "telegram_u1".to_string(); - histories.insert( - sender.clone(), - (0..20) - .map(|idx| { - let content = format!("msg-{idx}-{}", "x".repeat(700)); - if idx % 2 == 0 { - ChatMessage::user(content) - } else { - ChatMessage::assistant(content) - } - }) - .collect::>(), - ); - - let ctx = ChannelRuntimeContext { - channels_by_name: Arc::new(HashMap::new()), - turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(Arc::new( - DummyModel, - ))), - default_provider: Arc::new("test-provider".to_string()), - memory: Arc::new(super::common::NoopMemory), - tools_registry: Arc::new(vec![]), - system_prompt: crate::channels::ChannelSystemPrompt::fixed("system"), - model: Arc::new("test-model".to_string()), - temperature: 0.0, - auto_save_memory: false, - max_tool_iterations: 5, - min_relevance_score: 0.0, - conversation_histories: Arc::new(Mutex::new(histories)), - turn_model_source_cache: Arc::new(Mutex::new(HashMap::new())), - route_overrides: Arc::new(Mutex::new(HashMap::new())), - api_url: None, - inference_url: None, - reliability: Arc::new(crate::config::ReliabilityConfig::default()), - multimodal: crate::config::MultimodalConfig::default(), - multimodal_files: crate::config::MultimodalFileConfig::default(), - config: None, - provider_runtime_options: - crate::inference::provider::ProviderRuntimeOptions::default(), - workspace_dir: Arc::new(std::env::temp_dir()), - message_timeout_secs: CHANNEL_MESSAGE_TIMEOUT_SECS, - }; - - assert!(compact_sender_history(&ctx, &sender)); - - let histories = ctx - .conversation_histories - .lock() - .unwrap_or_else(|e| e.into_inner()); - let kept = histories - .get(&sender) - .expect("sender history should remain"); - assert_eq!(kept.len(), CHANNEL_HISTORY_COMPACT_KEEP_MESSAGES); - assert!(kept.iter().all(|turn| { - let len = turn.content.chars().count(); - len <= CHANNEL_HISTORY_COMPACT_CONTENT_CHARS - || (len <= CHANNEL_HISTORY_COMPACT_CONTENT_CHARS + 3 && turn.content.ends_with("...")) - })); -} - -// ── conversation_history_key tests ───────────────────────────────────────── - -fn make_channel_msg(channel: &str, thread_ts: Option<&str>) -> traits::ChannelMessage { - traits::ChannelMessage { - id: "test_id".to_string(), - sender: "alice".to_string(), - reply_target: "chat-1".to_string(), - content: "hello".to_string(), - channel: channel.to_string(), - timestamp: 1, - thread_ts: thread_ts.map(ToString::to_string), - } -} - -/// Telegram uses thread_ts for reply targeting only; it must not split history. -#[test] -fn telegram_history_key_is_thread_ts_agnostic() { - let no_thread = make_channel_msg("telegram", None); - let with_thread = make_channel_msg("telegram", Some("99")); - let other_thread = make_channel_msg("telegram", Some("777")); - - let key_base = conversation_history_key(&no_thread); - let key_a = conversation_history_key(&with_thread); - let key_b = conversation_history_key(&other_thread); - - assert_eq!( - key_base, key_a, - "telegram: thread_ts must not change history key" - ); - assert_eq!( - key_a, key_b, - "telegram: different thread_ts must share history key" - ); -} - -/// For every other channel (e.g. Slack, Discord), thread_ts splits conversation -/// history so each thread is an independent context. -#[test] -fn non_telegram_history_key_differs_by_thread_ts() { - let no_thread = make_channel_msg("slack", None); - let with_thread = make_channel_msg("slack", Some("1234567890.000001")); - - let key_base = conversation_history_key(&no_thread); - let key_thread = conversation_history_key(&with_thread); - - assert_ne!( - key_base, key_thread, - "non-telegram channels must produce distinct keys for different thread_ts values" - ); -} diff --git a/crates/openhuman-core/src/channels/tests/discord_integration.rs b/crates/openhuman-core/src/channels/tests/discord_integration.rs index 357b0db1800..0fbccb00419 100644 --- a/crates/openhuman-core/src/channels/tests/discord_integration.rs +++ b/crates/openhuman-core/src/channels/tests/discord_integration.rs @@ -30,7 +30,6 @@ use super::super::runtime::process_channel_message; use super::super::traits; use super::super::{Channel, SendMessage}; use super::common::HistoryCaptureModel; -use crate::agent::bus::{mock_agent_run_turn, AgentTurnResponse}; use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; @@ -311,70 +310,3 @@ async fn discord_thread_ts_splits_conversation_history_end_to_end() { "thread-B history MUST NOT leak content from thread-A" ); } - -// ── 4. Encapsulation money shot: stub the agent bus handler ──────────────── - -/// Full encapsulation proof: install a stub `agent.run_turn` bus handler, -/// drive a Discord message end-to-end, assert the stub was called exactly -/// once and its canned response reached the channel. This is the end-to-end -/// coverage that closes the decoupling loop for the Discord dispatch path — -/// if dispatch ever reverts to calling `run_tool_call_loop` directly, this -/// test starts failing because the stub handler won't be invoked. -#[tokio::test] -async fn discord_dispatch_routes_through_agent_run_turn_bus_handler() { - // Install a stub `agent.run_turn` handler via the shared mock bus - // helper. The returned guard holds `BUS_HANDLER_LOCK` for the whole - // test body and re-registers production handlers on drop — even on - // panic — so no manual restore call is required. - let stub_calls = Arc::new(AtomicUsize::new(0)); - let stub_calls_for_handler = Arc::clone(&stub_calls); - let _bus_guard = mock_agent_run_turn(move |req| { - let stub_calls = Arc::clone(&stub_calls_for_handler); - async move { - stub_calls.fetch_add(1, Ordering::SeqCst); - // Sanity-check the payload the dispatcher built for us. - assert_eq!(req.channel_name, "discord"); - assert_eq!(req.provider_name, "test-provider"); - assert_eq!(req.model, "test-model"); - assert!( - req.history.len() >= 2, - "history should include at least the system prompt and user message" - ); - Ok(AgentTurnResponse::new("CANNED_DISCORD_RESPONSE")) - } - }) - .await; - - let recorder = Arc::new(DiscordRecordingChannel::default()); - let channel: Arc = recorder.clone(); - // Minimal provider — never invoked because the stub short-circuits. - let ctx = make_discord_ctx(channel, Arc::new(super::common::DummyModel)); - - process_channel_message( - ctx, - traits::ChannelMessage { - id: "discord_stub_msg".to_string(), - sender: "user-123".to_string(), - reply_target: "channel-456".to_string(), - content: "hello via stub".to_string(), - channel: "discord".to_string(), - timestamp: 1, - thread_ts: None, - }, - ) - .await; - - assert_eq!( - stub_calls.load(Ordering::SeqCst), - 1, - "discord dispatch must route through the agent.run_turn bus handler exactly once" - ); - - let sent = recorder.sent.lock().await; - assert_eq!(sent.len(), 1, "stubbed response must reach the channel"); - assert!( - sent[0].content.contains("CANNED_DISCORD_RESPONSE"), - "delivered message should contain the stubbed text, got {:?}", - sent[0].content - ); -} diff --git a/crates/openhuman-core/src/channels/tests/mod.rs b/crates/openhuman-core/src/channels/tests/mod.rs index c9b57313d47..526f377db34 100644 --- a/crates/openhuman-core/src/channels/tests/mod.rs +++ b/crates/openhuman-core/src/channels/tests/mod.rs @@ -12,10 +12,6 @@ //! `NoopMemory`, a `MockPriceTool`, `make_workspace` for identity-file //! fixtures, and a re-export of `agent::bus::use_real_agent_handler`. //! -//! `context.rs` sits in this directory but is not declared below, so it does -//! not compile; the live coverage for `channels/context.rs` is -//! `channels/context_tests.rs`. -//! //! * `discord_integration.rs` — end-to-end dispatch through the Discord //! channel with every cross-module boundary (agent runtime, memory, //! provider) substituted, proving the domain stays encapsulated. @@ -25,9 +21,6 @@ //! markdown into the Project Context section. //! * `memory.rs` — conversation-history and memory-context wiring through //! `process_channel_message`. -//! * `personality.rs` — acceptance coverage for #6027/#6028 (channel turns -//! carry the active personality; identity edits reach the next turn -//! without a restart). //! * `prompt.rs` — system-prompt section assembly and bootstrap truncation. //! * `runtime_dispatch.rs` — the dispatch loop through //! `runtime::test_support::run_dispatch_harness`: inbound-envelope diff --git a/crates/openhuman-core/src/channels/tests/runtime_dispatch.rs b/crates/openhuman-core/src/channels/tests/runtime_dispatch.rs index 1b7c3eaa8a1..07712a6f7a3 100644 --- a/crates/openhuman-core/src/channels/tests/runtime_dispatch.rs +++ b/crates/openhuman-core/src/channels/tests/runtime_dispatch.rs @@ -616,3 +616,19 @@ async fn process_channel_message_hardens_against_relative_path_markers() { assert_eq!(observed.max_files, 0); assert!(!observed.allow_remote_fetch); } + +#[tokio::test] +async fn dispatch_replies_with_timeout_notice_when_handler_exceeds_deadline() { + let timed_out = run_dispatch_harness(DispatchHarnessOptions { + channel_name: "email".to_string(), + content: "force timeout".to_string(), + handler_delay_ms: 1_200, + timeout_secs: 1, + ..Default::default() + }) + .await; + assert!(timed_out + .sends + .iter() + .any(|send| send.content.contains("Request timed out"))); +} diff --git a/crates/openhuman-core/src/channels/tests/telegram_integration.rs b/crates/openhuman-core/src/channels/tests/telegram_integration.rs index 59b74fcdbee..1f0a78b0b76 100644 --- a/crates/openhuman-core/src/channels/tests/telegram_integration.rs +++ b/crates/openhuman-core/src/channels/tests/telegram_integration.rs @@ -12,7 +12,6 @@ use super::super::runtime::process_channel_message; use super::super::traits; use super::super::{Channel, SendMessage}; use super::common::SlowModel; -use crate::agent::bus::{mock_agent_run_turn, AgentTurnResponse}; use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; @@ -430,80 +429,6 @@ async fn telegram_threaded_inbound_emits_ack_reaction_then_reply() { ); } -/// Full encapsulation proof (parity with -/// `discord_dispatch_routes_through_agent_run_turn_bus_handler`): install a -/// stub `agent.run_turn` bus handler, drive a Telegram-shaped inbound -/// message end-to-end, and assert the stub is invoked and its canned -/// response reaches the channel. Together with the Discord counterpart, -/// this proves the channels module can be fully exercised for BOTH -/// Telegram and Discord without touching any real agent runtime, memory -/// backend, or LLM provider. -#[tokio::test] -async fn telegram_dispatch_routes_through_agent_run_turn_bus_handler() { - // Install a typed stub for `agent.run_turn` via the shared mock bus - // helper. The returned guard holds `BUS_HANDLER_LOCK` for the whole - // test body and re-registers production handlers on drop. - let stub_calls = Arc::new(AtomicUsize::new(0)); - let stub_calls_for_handler = Arc::clone(&stub_calls); - let _bus_guard = mock_agent_run_turn(move |req| { - let stub_calls = Arc::clone(&stub_calls_for_handler); - async move { - stub_calls.fetch_add(1, Ordering::SeqCst); - // Sanity-check the payload the dispatcher built for us. - assert_eq!(req.channel_name, "telegram"); - assert_eq!(req.provider_name, "test-provider"); - assert_eq!(req.model, "test-model"); - assert!( - req.history.len() >= 2, - "history should include at least the system prompt and user message" - ); - Ok(AgentTurnResponse::new("CANNED_TELEGRAM_RESPONSE")) - } - }) - .await; - - // Use the TelegramReactingChannel so the channel genuinely reports - // `name() == "telegram"`. This makes the `req.channel_name == "telegram"` - // assertion above a real encapsulation check: dispatch must look up the - // Telegram channel by its real name and build the bus request accordingly. - let recorder = Arc::new(TelegramReactingChannel::default()); - let channel: Arc = recorder.clone(); - // Minimal provider — never invoked because the stub short-circuits. - let ctx = make_test_context(channel, Arc::new(super::common::DummyModel)); - - process_channel_message( - ctx, - traits::ChannelMessage { - id: "tg_stub_msg".to_string(), - sender: "alice".to_string(), - reply_target: "alice".to_string(), - content: "hello from telegram bus test".to_string(), - channel: "telegram".to_string(), - timestamp: 1, - // No thread_ts so dispatch does not emit an automatic ack - // reaction — we want to count exactly one send. - thread_ts: None, - }, - ) - .await; - - assert_eq!( - stub_calls.load(Ordering::SeqCst), - 1, - "telegram dispatch must route through the agent.run_turn bus handler exactly once" - ); - - let sent = recorder.sent.lock().await; - assert_eq!(sent.len(), 1, "stubbed response must reach the channel"); - assert!( - sent[0].content.contains("CANNED_TELEGRAM_RESPONSE"), - "delivered message should contain the stubbed text, got {:?}", - sent[0].content - ); - // No manual restore — dropping `_bus_guard` at end-of-scope re-registers - // the production `agent.run_turn` handler automatically. -} - /// Regression: for non-Telegram channels, thread_ts DOES split history keys /// so each thread maintains independent conversation context. #[test] diff --git a/crates/openhuman-core/src/commands/schemas_tests.rs b/crates/openhuman-core/src/commands/schemas_tests.rs index 51c4c6e22c5..7b9179a92c9 100644 --- a/crates/openhuman-core/src/commands/schemas_tests.rs +++ b/crates/openhuman-core/src/commands/schemas_tests.rs @@ -19,13 +19,6 @@ fn list_schema_has_no_required_inputs() { assert_eq!(schema.outputs[0].name, "commands"); } -#[test] -fn unknown_function_falls_back_to_an_error_schema() { - let schema = schemas("does_not_exist"); - assert_eq!(schema.function, "unknown"); - assert_eq!(schema.outputs[0].name, "error"); -} - #[tokio::test] async fn handle_list_returns_every_builtin() { use serde_json::Map; diff --git a/crates/openhuman-core/src/config/migration_helpers/schemas_tests.rs b/crates/openhuman-core/src/config/migration_helpers/schemas_tests.rs index ef355e7ff29..4c4699458b5 100644 --- a/crates/openhuman-core/src/config/migration_helpers/schemas_tests.rs +++ b/crates/openhuman-core/src/config/migration_helpers/schemas_tests.rs @@ -32,14 +32,6 @@ fn openclaw_schema_describes_optional_source_and_dry_run() { assert_eq!(s.outputs[0].name, "report"); } -#[test] -fn unknown_function_returns_unknown_placeholder() { - let s = schemas("bogus"); - assert_eq!(s.function, "unknown"); - assert_eq!(s.namespace, "migrate"); - assert_eq!(s.outputs[0].name, "error"); -} - #[test] fn migrate_openclaw_params_tolerates_empty_object() { let params: MigrateOpenClawParams = serde_json::from_value(json!({})).unwrap(); diff --git a/crates/openhuman-core/src/config/mod.rs b/crates/openhuman-core/src/config/mod.rs index 094c19da9dd..56b7ddff9a0 100644 --- a/crates/openhuman-core/src/config/mod.rs +++ b/crates/openhuman-core/src/config/mod.rs @@ -29,9 +29,9 @@ pub use ops::*; pub use schema::{ action_dir_env_override, active_user_marker_path, active_workspace_dir, active_workspace_dir_cached, active_workspace_snapshot, clear_active_user, default_action_dir, - default_projects_dir, default_root_openhuman_dir, is_legacy_tier_model, legacy_tier_role, - pre_login_user_dir, read_active_user_id, resolve_action_dir, user_openhuman_dir, - write_active_user_id, PRE_LOGIN_USER_ID, WORKLOAD_ROLES, + default_files_dir, default_projects_dir, default_root_openhuman_dir, is_legacy_tier_model, + legacy_tier_role, pre_login_user_dir, read_active_user_id, resolve_action_dir, + resolve_files_dir, user_openhuman_dir, write_active_user_id, PRE_LOGIN_USER_ID, WORKLOAD_ROLES, }; pub use workspace_handle::workspace_handle; // Crate-internal: workspace→config-dir resolver reused by the cloud embedder. diff --git a/crates/openhuman-core/src/config/ops/agent.rs b/crates/openhuman-core/src/config/ops/agent.rs index abcee09ecc6..89e994664f3 100644 --- a/crates/openhuman-core/src/config/ops/agent.rs +++ b/crates/openhuman-core/src/config/ops/agent.rs @@ -59,13 +59,16 @@ pub struct AgentSettingsPatch { /// Partial update for the agent's editable filesystem roots. /// -/// Only `action_dir` is editable today (issue #3240). `workspace_dir` and -/// `projects_dir` are intentionally read-only and not part of this patch. +/// `action_dir` (issue #3240) and the files folder (#5505) are editable. +/// `workspace_dir` and `projects_dir` are intentionally read-only. #[derive(Debug, Clone, Default)] pub struct AgentPathsPatch { /// New action sandbox root. `Some("")`/whitespace clears the override and /// reverts to the default; `Some(path)` sets it; `None` leaves it unchanged. pub action_dir: Option, + /// New folder for agent deliverables. Same `Some("")` / `Some(path)` / + /// `None` semantics as `action_dir`. Affects new artifacts only. + pub files_dir: Option, } /// Patch for the global memory-sync cadence (#3302). @@ -401,6 +404,28 @@ pub async fn ensure_agent_dirs(config: &mut Config) { action = %redact_home(&action_dir), "[startup] workspace (internal state) and action sandbox (tool cwd) directories configured" ); + + // Agent deliverables are written to the visible files folder (#5505). + // Create it up front, and move this account's pre-#5505 artifact files out + // of the hidden workspace (idempotent; a no-op once migrated). + let files_dir = config.files_dir(); + if let Err(e) = tokio::fs::create_dir_all(&files_dir).await { + tracing::warn!( + dir = %redact_home(&files_dir), + error = %e, + "[startup] could not create files folder" + ); + } + let report = + crate::agent::artifacts::migrate_legacy_artifacts(&config.workspace_dir, &files_dir).await; + if report != crate::agent::artifacts::MigrationReport::default() { + tracing::info!( + moved = report.moved, + cleaned = report.cleaned, + failed = report.failed, + "[startup] moved legacy artifact files into the files folder" + ); + } } /// Ensure `dir` is usable as a process working directory: it must exist (we @@ -446,9 +471,75 @@ fn agent_paths_payload(config: &Config) -> serde_json::Value { "workspace_dir": config.workspace_dir.display().to_string(), "projects_dir": projects_dir.display().to_string(), "action_dir_source": action_dir_source(config), + "files_dir": config.files_dir().display().to_string(), + "default_files_dir": crate::config::default_files_dir().display().to_string(), + "files_dir_source": if config.files_dir_override.is_some() { "override" } else { "default" }, }) } +/// Validate a user-chosen files folder (#5505) and create it. Fail-closed: +/// the path must be absolute, not an existing file, not a protected location +/// (credential stores, OS directories), and not inside the OpenHuman data +/// directory — the point of the folder is that the user can see it, and the +/// data dir holds internal state. +async fn validate_files_dir(raw: &str, config: &Config) -> Result { + let expanded = expand_tilde(raw); + let candidate = PathBuf::from(&expanded); + if !candidate.is_absolute() { + return Err(format!( + "files_dir must be an absolute path (got '{expanded}')" + )); + } + if candidate.is_file() { + return Err(format!( + "files_dir must be a folder, not a file: {expanded}" + )); + } + if crate::security::SecurityPolicy::is_always_forbidden(&candidate) { + return Err(format!( + "files_dir cannot be a protected system or credential folder: {expanded}" + )); + } + let mut internal = vec![config.workspace_dir.clone()]; + if let Ok(root) = crate::config::default_root_openhuman_dir() { + internal.push(root); + } + if internal.iter().any(|dir| path_within(&candidate, dir)) { + return Err(format!( + "files_dir must not be inside the OpenHuman data folder: {expanded}" + )); + } + tokio::fs::create_dir_all(&candidate) + .await + .map_err(|e| format!("failed to create files_dir {expanded}: {e}"))?; + Ok(candidate) +} + +/// `path` equals or sits under `dir`, comparing canonical forms so a +/// symlinked spelling (e.g. macOS `/var` → `/private/var`) cannot slip into +/// the data dir. A path that does not exist yet is canonicalized through its +/// nearest existing ancestor. +fn path_within(path: &Path, dir: &Path) -> bool { + canonical_prefix(path).starts_with(canonical_prefix(dir)) +} + +fn canonical_prefix(path: &Path) -> PathBuf { + let mut rest = Vec::new(); + let mut cursor = path; + loop { + if let Ok(canon) = cursor.canonicalize() { + return rest.iter().rev().fold(canon, |acc, part| acc.join(part)); + } + match (cursor.parent(), cursor.file_name()) { + (Some(parent), Some(name)) => { + rest.push(name.to_os_string()); + cursor = parent; + } + _ => return path.to_path_buf(), + } + } +} + /// Applies an edit to the agent's `action_dir` sandbox root. /// /// Validation (fail-closed): the path is trimmed and `~`-expanded; it must be @@ -529,6 +620,34 @@ pub async fn apply_agent_paths_settings( ); } + if let Some(raw) = update.files_dir { + let trimmed = raw.trim(); + log::debug!( + "[config][agent_paths] apply files_dir edit (input_len={})", + trimmed.len() + ); + let previous = config.files_dir(); + if trimmed.is_empty() { + config.files_dir_override = None; + notes.push("files_dir override cleared (reverted to default)".to_string()); + } else { + let candidate = validate_files_dir(trimmed, config).await?; + notes.push(format!("files_dir set to {}", candidate.display())); + config.files_dir_override = Some(candidate); + } + // Existing artifacts stay where they are, so the folder they were + // made in must stay trusted by the artifact escape guard. + if previous != config.files_dir() && !config.files_dir_history.contains(&previous) { + config.files_dir_history.push(previous); + } + config.save().await.map_err(|e| e.to_string())?; + crate::core::bus::BUS.publish(crate::core::events::DomainEvent::AgentPathsChanged); + log::debug!( + "[config][agent_paths] files_dir now '{}'", + config.files_dir().display() + ); + } + Ok(Outcome::new(agent_paths_payload(config), notes)) } diff --git a/crates/openhuman-core/src/config/ops_agent_paths_tests.rs b/crates/openhuman-core/src/config/ops_agent_paths_tests.rs index 80b29ed6190..6f47f7b427d 100644 --- a/crates/openhuman-core/src/config/ops_agent_paths_tests.rs +++ b/crates/openhuman-core/src/config/ops_agent_paths_tests.rs @@ -141,6 +141,7 @@ async fn apply_agent_paths_valid_abs_path_persists_override_and_recomputes() { &mut cfg, AgentPathsPatch { action_dir: Some(new_dir.to_string_lossy().to_string()), + files_dir: None, }, ) .await @@ -171,6 +172,7 @@ async fn apply_agent_paths_rejects_relative_path() { &mut cfg, AgentPathsPatch { action_dir: Some("relative/projects".into()), + files_dir: None, }, ) .await @@ -194,6 +196,7 @@ async fn apply_agent_paths_rejects_action_dir_equal_to_workspace() { &mut cfg, AgentPathsPatch { action_dir: Some(workspace.to_string_lossy().to_string()), + files_dir: None, }, ) .await @@ -220,6 +223,7 @@ async fn apply_agent_paths_empty_input_clears_override() { &mut cfg, AgentPathsPatch { action_dir: Some(" ".into()), + files_dir: None, }, ) .await @@ -249,6 +253,7 @@ async fn apply_agent_paths_auto_creates_missing_directory() { &mut cfg, AgentPathsPatch { action_dir: Some(missing.to_string_lossy().to_string()), + files_dir: None, }, ) .await @@ -273,6 +278,7 @@ async fn apply_agent_paths_rejects_existing_file() { &mut cfg, AgentPathsPatch { action_dir: Some(file.to_string_lossy().to_string()), + files_dir: None, }, ) .await @@ -302,6 +308,7 @@ async fn apply_agent_paths_env_set_reports_source_env() { &mut cfg, AgentPathsPatch { action_dir: Some(user_dir.to_string_lossy().to_string()), + files_dir: None, }, ) .await diff --git a/crates/openhuman-core/src/config/ops_files_dir_tests.rs b/crates/openhuman-core/src/config/ops_files_dir_tests.rs new file mode 100644 index 00000000000..c1bed915c8d --- /dev/null +++ b/crates/openhuman-core/src/config/ops_files_dir_tests.rs @@ -0,0 +1,228 @@ +//! The files folder setting (#5505): where agent deliverables are written. + +use super::*; + +fn patch(files_dir: &str) -> AgentPathsPatch { + AgentPathsPatch { + action_dir: None, + files_dir: Some(files_dir.to_string()), + } +} + +#[tokio::test] +async fn setting_the_files_folder_persists_it_and_creates_it() { + let tmp = tempdir().unwrap(); + let mut cfg = tmp_config(&tmp); + let chosen = tmp.path().join("Deliverables"); + + let outcome = apply_agent_paths_settings(&mut cfg, patch(&chosen.to_string_lossy())) + .await + .expect("apply files_dir"); + + assert!(chosen.is_dir(), "a missing folder is created"); + assert_eq!(cfg.files_dir_override.as_deref(), Some(chosen.as_path())); + assert_eq!(cfg.files_dir(), chosen); + assert_eq!( + outcome.value["files_dir"], + serde_json::json!(chosen.display().to_string()) + ); + assert_eq!( + outcome.value["files_dir_source"], + serde_json::json!("override") + ); + let saved = std::fs::read_to_string(&cfg.config_path).expect("config saved"); + assert!(saved.contains("files_dir_override"), "{saved}"); +} + +#[tokio::test] +async fn an_empty_value_reverts_to_the_default_folder() { + let tmp = tempdir().unwrap(); + let mut cfg = tmp_config(&tmp); + cfg.files_dir_override = Some(tmp.path().join("Old")); + + let outcome = apply_agent_paths_settings(&mut cfg, patch(" ")) + .await + .expect("clear files_dir"); + + assert!(cfg.files_dir_override.is_none()); + assert_eq!(cfg.files_dir(), crate::config::default_files_dir()); + assert_eq!( + outcome.value["files_dir_source"], + serde_json::json!("default") + ); + assert_eq!( + outcome.value["default_files_dir"], + serde_json::json!(crate::config::default_files_dir().display().to_string()) + ); +} + +async fn rejected(cfg: &mut Config, value: &str) -> String { + let before = cfg.files_dir_override.clone(); + let err = apply_agent_paths_settings(cfg, patch(value)) + .await + .expect_err("files_dir must be rejected"); + assert_eq!( + cfg.files_dir_override, before, + "a rejected value is not stored" + ); + err +} + +#[tokio::test] +async fn a_relative_path_is_rejected() { + let tmp = tempdir().unwrap(); + let mut cfg = tmp_config(&tmp); + let err = rejected(&mut cfg, "relative/Files").await; + assert!(err.contains("absolute"), "{err}"); +} + +#[tokio::test] +async fn a_file_is_rejected() { + let tmp = tempdir().unwrap(); + let mut cfg = tmp_config(&tmp); + let file = tmp.path().join("not-a-folder.txt"); + std::fs::write(&file, b"x").unwrap(); + let err = rejected(&mut cfg, &file.to_string_lossy()).await; + assert!(err.contains("not a file"), "{err}"); +} + +#[tokio::test] +async fn a_folder_inside_the_openhuman_data_folder_is_rejected() { + let tmp = tempdir().unwrap(); + let mut cfg = tmp_config(&tmp); + let inside = cfg.workspace_dir.join("Files"); + let err = rejected(&mut cfg, &inside.to_string_lossy()).await; + assert!(err.contains("OpenHuman data folder"), "{err}"); + assert!(!inside.exists(), "nothing is created for a rejected value"); +} + +#[tokio::test] +async fn a_credential_folder_is_rejected() { + let tmp = tempdir().unwrap(); + let mut cfg = tmp_config(&tmp); + let ssh = tmp.path().join(".ssh").join("Files"); + let err = rejected(&mut cfg, &ssh.to_string_lossy()).await; + assert!(err.contains("protected"), "{err}"); +} + +#[test] +fn a_relative_override_on_disk_falls_back_to_the_default() { + let cfg = Config { + files_dir_override: Some(PathBuf::from("relative")), + ..Config::default() + }; + assert_eq!(cfg.files_dir(), crate::config::default_files_dir()); +} + +/// The boot migration moves legacy files into the folder the user chose, not +/// the default one. +#[tokio::test] +async fn boot_migrates_legacy_files_into_the_chosen_folder() { + use crate::agent::artifacts::store::save_artifact_meta; + use crate::agent::artifacts::{ArtifactKind, ArtifactMeta, ArtifactStatus}; + + let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let tmp = tempdir().unwrap(); + let prev_projects_dir = std::env::var_os("OPENHUMAN_PROJECTS_DIR"); + unsafe { + std::env::set_var("OPENHUMAN_PROJECTS_DIR", tmp.path().join("projects-home")); + } + + let mut cfg = tmp_config(&tmp); + cfg.action_dir = tmp.path().join("action"); + let chosen = tmp.path().join("Chosen"); + cfg.files_dir_override = Some(chosen.clone()); + let meta = ArtifactMeta { + id: "legacy".to_string(), + kind: ArtifactKind::Document, + title: "Plan".to_string(), + path: "legacy/plan.docx".to_string(), + file: None, + file_root: None, + size_bytes: 4, + status: ArtifactStatus::Ready, + created_at: chrono::Utc::now(), + error: None, + thread_id: None, + tool_call_id: None, + }; + save_artifact_meta(&cfg.workspace_dir, &meta).await.unwrap(); + std::fs::write( + cfg.workspace_dir.join("artifacts/legacy/plan.docx"), + b"plan", + ) + .unwrap(); + + crate::config::ensure_agent_dirs(&mut cfg).await; + + unsafe { + match prev_projects_dir { + Some(v) => std::env::set_var("OPENHUMAN_PROJECTS_DIR", v), + None => std::env::remove_var("OPENHUMAN_PROJECTS_DIR"), + } + } + assert_eq!(std::fs::read(chosen.join("plan.docx")).unwrap(), b"plan"); +} + +/// A symlinked spelling of the data folder is still the data folder: the +/// check compares canonical paths, not text. +#[cfg(unix)] +#[tokio::test] +async fn a_symlinked_route_into_the_data_folder_is_rejected() { + let tmp = tempdir().unwrap(); + let mut cfg = tmp_config(&tmp); + let alias = tmp.path().join("alias"); + std::os::unix::fs::symlink(&cfg.workspace_dir, &alias).unwrap(); + + let err = rejected(&mut cfg, &alias.join("Files").to_string_lossy()).await; + assert!(err.contains("OpenHuman data folder"), "{err}"); +} + +/// Changing the folder affects new files only: a file made in the previous +/// folder keeps resolving, because that folder is recorded as trusted. +#[tokio::test] +async fn files_made_before_a_folder_change_keep_resolving() { + use crate::agent::artifacts::store::{create_artifact, finalize_artifact}; + use crate::agent::artifacts::{ArtifactKind, FileRoots}; + + let tmp = tempdir().unwrap(); + let mut cfg = tmp_config(&tmp); + let first = tmp.path().join("First"); + let second = tmp.path().join("Second"); + apply_agent_paths_settings(&mut cfg, patch(&first.to_string_lossy())) + .await + .unwrap(); + let (meta, path) = create_artifact( + &cfg.workspace_dir, + FileRoots::from_config(&cfg), + ArtifactKind::Document, + "Plan", + "docx", + ) + .await + .unwrap(); + std::fs::write(&path, b"plan").unwrap(); + finalize_artifact(&cfg.workspace_dir, &meta.id, 4) + .await + .unwrap(); + assert!(path.starts_with(&first)); + + apply_agent_paths_settings(&mut cfg, patch(&second.to_string_lossy())) + .await + .unwrap(); + + assert!( + cfg.files_dir_history.contains(&first), + "{:?}", + cfg.files_dir_history + ); + let value = crate::agent::artifacts::ops::ai_get_artifact(&cfg, &meta.id) + .await + .expect("an artifact from the previous folder still resolves") + .into_cli_compatible_json() + .unwrap(); + assert_eq!( + value["absolute_path"], + serde_json::json!(path.to_string_lossy()) + ); +} diff --git a/crates/openhuman-core/src/config/ops_tests.rs b/crates/openhuman-core/src/config/ops_tests.rs index d0ac24f025d..b2b1ae446f6 100644 --- a/crates/openhuman-core/src/config/ops_tests.rs +++ b/crates/openhuman-core/src/config/ops_tests.rs @@ -17,6 +17,8 @@ fn tmp_config(tmp: &tempfile::TempDir) -> Config { #[path = "ops_agent_paths_tests.rs"] mod agent_paths_tests; +#[path = "ops_files_dir_tests.rs"] +mod files_dir_tests; #[path = "ops_loader_and_search_tests.rs"] mod loader_and_search_tests; #[path = "ops_model_and_local_ai_tests.rs"] diff --git a/crates/openhuman-core/src/config/schema/load/dirs.rs b/crates/openhuman-core/src/config/schema/load/dirs.rs index 9c694d4dd42..25eed92e790 100644 --- a/crates/openhuman-core/src/config/schema/load/dirs.rs +++ b/crates/openhuman-core/src/config/schema/load/dirs.rs @@ -91,6 +91,32 @@ pub fn default_projects_dir() -> PathBuf { .join("projects") } +/// Name of the visible folder, under the projects home, that holds the files +/// the agent delivers (decks, documents, generated media) — see #5505. +pub const FILES_DIRNAME: &str = "Files"; + +/// Where agent deliverables are written by default: `~/OpenHuman/projects/Files`. +/// Only the bytes live here; each artifact's metadata stays in the hidden, +/// per-account `/artifacts//`. +pub fn default_files_dir() -> PathBuf { + default_projects_dir().join(FILES_DIRNAME) +} + +/// Resolve the effective files folder: the persisted override when it is a +/// non-empty absolute path, else [`default_files_dir`]. +pub fn resolve_files_dir(files_dir_override: &Option) -> PathBuf { + match files_dir_override { + Some(dir) if dir.is_absolute() => dir.clone(), + Some(_) => { + tracing::warn!( + "[config] ignoring invalid files_dir_override; expected an absolute path" + ); + default_files_dir() + } + None => default_files_dir(), + } +} + /// The `OPENHUMAN_ACTION_DIR` env override, when set to a non-empty value. /// /// Returns `None` when the variable is unset or blank (a common shape from diff --git a/crates/openhuman-core/src/config/schema/load/mod.rs b/crates/openhuman-core/src/config/schema/load/mod.rs index 2a116d32272..5822bd4b5c7 100644 --- a/crates/openhuman-core/src/config/schema/load/mod.rs +++ b/crates/openhuman-core/src/config/schema/load/mod.rs @@ -12,9 +12,10 @@ pub use active_workspace::active_workspace_dir_cached; pub(crate) use active_workspace::invalidate_active_workspace; pub use dirs::{ action_dir_env_override, active_user_marker_path, active_workspace_dir, - active_workspace_snapshot, clear_active_user, default_action_dir, default_projects_dir, - default_root_openhuman_dir, pre_login_user_dir, read_active_user_id, resolve_action_dir, - user_openhuman_dir, write_active_user_id, PRE_LOGIN_USER_ID, + active_workspace_snapshot, clear_active_user, default_action_dir, default_files_dir, + default_projects_dir, default_root_openhuman_dir, pre_login_user_dir, read_active_user_id, + resolve_action_dir, resolve_files_dir, user_openhuman_dir, write_active_user_id, + PRE_LOGIN_USER_ID, }; // redact_url_for_log is pub(super) for the schema module; tests inside load diff --git a/crates/openhuman-core/src/config/schema/load_active_user_and_dirs_tests.rs b/crates/openhuman-core/src/config/schema/load_active_user_and_dirs_tests.rs index 590b579b9ca..88818adaaef 100644 --- a/crates/openhuman-core/src/config/schema/load_active_user_and_dirs_tests.rs +++ b/crates/openhuman-core/src/config/schema/load_active_user_and_dirs_tests.rs @@ -98,11 +98,15 @@ fn user_openhuman_dir_builds_correct_path() { } #[tokio::test] -// Races on `OPENHUMAN_WORKSPACE` env var with other tests holding -// `TEST_ENV_LOCK` — passes in isolation, intermittently fails in parallel. -// Runs reliably with `--ignored --test-threads=1`. See PR #1524. -#[ignore = "flaky in parallel cargo test; OPENHUMAN_WORKSPACE env-var race — see PR #1524"] +#[allow(clippy::await_holding_lock)] async fn resolve_dirs_uses_active_user_when_present() { + // `resolve_runtime_config_dirs` reads `OPENHUMAN_WORKSPACE`; hold the shared + // env lock and clear it so a sibling test's override cannot leak in. + let _env_guard = crate::config::TEST_ENV_LOCK + .lock() + .unwrap_or_else(|e| e.into_inner()); + let prior_workspace = std::env::var_os("OPENHUMAN_WORKSPACE"); + std::env::remove_var("OPENHUMAN_WORKSPACE"); let tmp = tempfile::tempdir().unwrap(); let root = tmp.path(); let default_workspace = root.join("workspace"); @@ -126,6 +130,10 @@ async fn resolve_dirs_uses_active_user_when_present() { assert_eq!(oh_dir, expected_user_dir); assert_eq!(ws_dir, expected_user_dir.join("workspace")); assert_eq!(source, ConfigResolutionSource::ActiveUser); + + if let Some(value) = prior_workspace { + std::env::set_var("OPENHUMAN_WORKSPACE", value); + } } #[test] diff --git a/crates/openhuman-core/src/config/schema/mod.rs b/crates/openhuman-core/src/config/schema/mod.rs index 35cb99c9a92..9cb4bb79d67 100644 --- a/crates/openhuman-core/src/config/schema/mod.rs +++ b/crates/openhuman-core/src/config/schema/mod.rs @@ -35,8 +35,9 @@ mod load; pub use load::{ action_dir_env_override, active_user_marker_path, active_workspace_dir, active_workspace_dir_cached, active_workspace_snapshot, clear_active_user, default_action_dir, - default_projects_dir, default_root_openhuman_dir, pre_login_user_dir, read_active_user_id, - resolve_action_dir, user_openhuman_dir, write_active_user_id, PRE_LOGIN_USER_ID, + default_files_dir, default_projects_dir, default_root_openhuman_dir, pre_login_user_dir, + read_active_user_id, resolve_action_dir, resolve_files_dir, user_openhuman_dir, + write_active_user_id, PRE_LOGIN_USER_ID, }; // Crate-internal: the invalidation half of the cached active workspace. The // marker writers in `load_user_state` call it from outside `load`; the diff --git a/crates/openhuman-core/src/config/schema/types/config.rs b/crates/openhuman-core/src/config/schema/types/config.rs index 67e791a84fa..9e80960f279 100644 --- a/crates/openhuman-core/src/config/schema/types/config.rs +++ b/crates/openhuman-core/src/config/schema/types/config.rs @@ -73,6 +73,20 @@ pub struct Config { /// overrides at runtime so existing env-driven deployments are unaffected. #[serde(default)] pub action_dir_override: Option, + /// Persisted user choice for the folder agent deliverables are written to, + /// set via Settings → Agent OS access (`config.update_agent_paths`, + /// #5505). `None` means the default, `~/OpenHuman/projects/Files`. Read it + /// through [`Self::files_dir`]. Changing it affects new artifacts only; + /// existing ones keep the folder recorded in their metadata. + #[serde(default)] + pub files_dir_override: Option, + /// Files folders used before the current one. Artifacts created there keep + /// resolving, because the artifact escape guard trusts only folders the + /// core records here (plus the current one and the default), never a + /// folder an artifact's own metadata claims. Appended by + /// `config.update_agent_paths`. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub files_dir_history: Vec, #[serde(skip)] pub config_path: PathBuf, /// Per-load snapshot used to remove standalone CLI inference overrides diff --git a/crates/openhuman-core/src/config/schema/types/defaults.rs b/crates/openhuman-core/src/config/schema/types/defaults.rs index 871d37ff983..bbcff6b359f 100644 --- a/crates/openhuman-core/src/config/schema/types/defaults.rs +++ b/crates/openhuman-core/src/config/schema/types/defaults.rs @@ -28,6 +28,8 @@ impl Default for Config { workspace_dir: openhuman_dir.join("workspace"), action_dir: crate::config::default_action_dir(), action_dir_override: None, + files_dir_override: None, + files_dir_history: Vec::new(), config_path: openhuman_dir.join("config.toml"), cli_inference_snapshot: None, recovered_from_corruption: false, diff --git a/crates/openhuman-core/src/config/schema/types/resolvers.rs b/crates/openhuman-core/src/config/schema/types/resolvers.rs index d2c4299207b..be487101856 100644 --- a/crates/openhuman-core/src/config/schema/types/resolvers.rs +++ b/crates/openhuman-core/src/config/schema/types/resolvers.rs @@ -7,6 +7,13 @@ use super::output_language::output_language_directive; use crate::config::schema::Config; impl Config { + /// The folder agent deliverables are written to (#5505): the Settings + /// override when set, else `~/OpenHuman/projects/Files`. Every producer + /// and the boot migration read it through here. + pub fn files_dir(&self) -> PathBuf { + crate::config::resolve_files_dir(&self.files_dir_override) + } + /// Resolve the root directory where chunk `.md` files are stored. /// /// Resolution order: diff --git a/crates/openhuman-core/src/config/schemas/controllers/workspace.rs b/crates/openhuman-core/src/config/schemas/controllers/workspace.rs index e5e8b69f577..f6be4a882b7 100644 --- a/crates/openhuman-core/src/config/schemas/controllers/workspace.rs +++ b/crates/openhuman-core/src/config/schemas/controllers/workspace.rs @@ -145,6 +145,7 @@ pub(super) fn handle_update_agent_paths(params: Map) -> Controlle }; let patch = config_rpc::AgentPathsPatch { action_dir: update.action_dir, + files_dir: update.files_dir, }; match config_rpc::load_and_apply_agent_paths_settings(patch).await { Ok(outcome) => { diff --git a/crates/openhuman-core/src/config/schemas/helpers.rs b/crates/openhuman-core/src/config/schemas/helpers.rs index 71b9cadff55..de9d34fab03 100644 --- a/crates/openhuman-core/src/config/schemas/helpers.rs +++ b/crates/openhuman-core/src/config/schemas/helpers.rs @@ -237,6 +237,10 @@ pub(super) struct AgentPathsUpdate { /// New absolute action sandbox path. Empty string clears the override; /// omitted leaves it unchanged. Validated server-side. pub(super) action_dir: Option, + /// New absolute folder for agent deliverables (#5505). Empty string + /// clears the override; omitted leaves it unchanged. + #[serde(default)] + pub(super) files_dir: Option, } #[derive(Debug, Deserialize)] diff --git a/crates/openhuman-core/src/config/schemas/schema_defs/workspace.rs b/crates/openhuman-core/src/config/schemas/schema_defs/workspace.rs index 69bcfa3deee..0ee42b5668a 100644 --- a/crates/openhuman-core/src/config/schemas/schema_defs/workspace.rs +++ b/crates/openhuman-core/src/config/schemas/schema_defs/workspace.rs @@ -119,23 +119,28 @@ pub(super) fn lookup(function: &str) -> Option { inputs: vec![], outputs: vec![json_output( "paths", - "Resolved agent paths: action_dir (acting-tool CWD), workspace_dir (internal state, agent-blocked), projects_dir (default projects home), action_dir_source (env | override | default).", + "Resolved agent paths: action_dir (acting-tool CWD), workspace_dir (internal state, agent-blocked), projects_dir (default projects home), action_dir_source (env | override | default), files_dir (where agent deliverables are written), default_files_dir, files_dir_source (override | default).", )], }), "update_agent_paths" => Some( ControllerSchema { namespace: "config", function: "update_agent_paths", description: - "Update the agent's editable filesystem roots. Currently only action_dir (the acting-tool sandbox). The path must be absolute; a missing directory is auto-created; it cannot equal the internal workspace_dir. An empty string clears the override and reverts to the default. Applies to new sessions immediately (live policy hot-swap), no restart. OPENHUMAN_ACTION_DIR still overrides at runtime when set.", + "Update the agent's editable filesystem roots: action_dir (the acting-tool sandbox) and files_dir (the folder agent deliverables are written to; new artifacts only, and it may not sit inside the OpenHuman data folder). The path must be absolute; a missing directory is auto-created; it cannot equal the internal workspace_dir. An empty string clears the override and reverts to the default. Applies to new sessions immediately (live policy hot-swap), no restart. OPENHUMAN_ACTION_DIR still overrides at runtime when set.", inputs: vec![FieldSchema { name: "action_dir", ty: TypeSchema::Option(Box::new(TypeSchema::String)), comment: "New absolute action sandbox path. Empty string clears the override (revert to default). Omit to leave unchanged.", required: false, + }, FieldSchema { + name: "files_dir", + ty: TypeSchema::Option(Box::new(TypeSchema::String)), + comment: "New absolute folder for agent deliverables. Empty string clears the override (revert to ~/OpenHuman/projects/Files). Omit to leave unchanged.", + required: false, }], outputs: vec![json_output( "paths", - "Updated agent paths (same shape as get_agent_paths): action_dir, workspace_dir, projects_dir, action_dir_source.", + "Updated agent paths (same shape as get_agent_paths): action_dir, workspace_dir, projects_dir, action_dir_source, files_dir, default_files_dir, files_dir_source.", )], }), "get_onboarding_completed" => Some( ControllerSchema { diff --git a/crates/openhuman-core/src/config/schemas_tests.rs b/crates/openhuman-core/src/config/schemas_tests.rs index 7932f252b99..eb23573626e 100644 --- a/crates/openhuman-core/src/config/schemas_tests.rs +++ b/crates/openhuman-core/src/config/schemas_tests.rs @@ -1,14 +1,6 @@ use super::schema_defs::schemas; use super::*; -#[test] -fn catalog_counts_match_and_nonempty() { - let s = all_controller_schemas(); - let h = all_registered_controllers(); - assert_eq!(s.len(), h.len()); - assert!(s.len() >= 20, "config namespace should expose ≥20 fns"); -} - #[test] fn all_schemas_use_config_namespace_and_have_descriptions() { for s in all_controller_schemas() { @@ -18,13 +10,6 @@ fn all_schemas_use_config_namespace_and_have_descriptions() { } } -#[test] -fn unknown_function_returns_unknown_schema() { - let s = schemas("no_such_fn"); - assert_eq!(s.function, "unknown"); - assert_eq!(s.namespace, "config"); -} - #[test] fn every_registered_key_resolves_to_non_unknown_schema() { let keys = [ diff --git a/crates/openhuman-core/src/config/workspace/schemas_tests.rs b/crates/openhuman-core/src/config/workspace/schemas_tests.rs index 0f1ecfc3acc..b763762d94a 100644 --- a/crates/openhuman-core/src/config/workspace/schemas_tests.rs +++ b/crates/openhuman-core/src/config/workspace/schemas_tests.rs @@ -1,14 +1,5 @@ use super::*; -#[test] -fn all_schemas_use_workspace_namespace() { - let all = all_controller_schemas(); - assert_eq!(all.len(), 3); - for schema in &all { - assert_eq!(schema.namespace, "workspace"); - } -} - #[test] fn registered_controllers_expose_expected_rpc_methods() { let methods: Vec = all_registered_controllers() @@ -27,9 +18,3 @@ fn file_write_schema_requires_filename_and_contents() { assert!(input_names.contains(&"filename")); assert!(input_names.contains(&"contents")); } - -#[test] -fn unknown_function_yields_unknown_schema() { - let schema = schemas("nope"); - assert_eq!(schema.function, "unknown"); -} diff --git a/crates/openhuman-core/src/core/core_mod_tests.rs b/crates/openhuman-core/src/core/core_mod_tests.rs index b912c776845..f05087371c0 100644 --- a/crates/openhuman-core/src/core/core_mod_tests.rs +++ b/crates/openhuman-core/src/core/core_mod_tests.rs @@ -34,59 +34,6 @@ fn method_name_preserves_underscores_in_function() { assert_eq!(s.method_name(), "team.change_member_role"); } -#[test] -fn controller_schema_equality_considers_all_fields() { - let a = ControllerSchema { - namespace: "a", - function: "b", - description: "x", - inputs: vec![], - outputs: vec![], - }; - let b = ControllerSchema { - namespace: "a", - function: "b", - description: "x", - inputs: vec![], - outputs: vec![], - }; - let c = ControllerSchema { - namespace: "a", - function: "b", - description: "different", - inputs: vec![], - outputs: vec![], - }; - assert_eq!(a, b); - assert_ne!(a, c); -} - -#[test] -fn type_schema_nesting_is_equality_comparable() { - let a = TypeSchema::Array(Box::new(TypeSchema::Option(Box::new(TypeSchema::String)))); - let b = TypeSchema::Array(Box::new(TypeSchema::Option(Box::new(TypeSchema::String)))); - let c = TypeSchema::Array(Box::new(TypeSchema::Option(Box::new(TypeSchema::I64)))); - assert_eq!(a, b); - assert_ne!(a, c); -} - -#[test] -fn field_schema_required_flag_changes_equality() { - let a = FieldSchema { - name: "x", - ty: TypeSchema::Bool, - comment: "", - required: true, - }; - let b = FieldSchema { - name: "x", - ty: TypeSchema::Bool, - comment: "", - required: false, - }; - assert_ne!(a, b); -} - #[test] fn controller_schema_serializes_to_json() { // Schema must be JSON-serializable: the /schema endpoint depends on it. diff --git a/crates/openhuman-core/src/core/events.rs b/crates/openhuman-core/src/core/events.rs index 865513477be..0a7cbb7955b 100644 --- a/crates/openhuman-core/src/core/events.rs +++ b/crates/openhuman-core/src/core/events.rs @@ -822,8 +822,8 @@ pub enum DomainEvent { /// relative and would otherwise resolve into the wrong /// `/artifacts/` tree. workspace_dir: String, - /// Relative path under `/artifacts/`, e.g. - /// `"/deck.pptx"`. The absolute path is reachable via + /// File name relative to its root (`"deck.pptx"` in the files folder, + /// legacy `"/deck.pptx"`); the absolute path is reachable via /// `ai_get_artifact` so the renderer never needs the /// workspace root. path: String, @@ -888,8 +888,8 @@ pub enum DomainEvent { /// Absolute workspace root the artifact belongs to — see /// [`Self::ArtifactReady::workspace_dir`] for rationale. workspace_dir: String, - /// Relative path under `/artifacts/` where the file - /// *will* land. The frontend uses it to render a stable card key + /// The name, relative to the visible files folder (#5505), the file + /// *will* land under. The frontend uses it to render a stable card key /// so subsequent `ArtifactReady` can swap the same surface in /// place without flicker. path: String, diff --git a/crates/openhuman-core/src/core/legacy_aliases_tests.rs b/crates/openhuman-core/src/core/legacy_aliases_tests.rs index c6dc5603f5d..a4395c59df9 100644 --- a/crates/openhuman-core/src/core/legacy_aliases_tests.rs +++ b/crates/openhuman-core/src/core/legacy_aliases_tests.rs @@ -154,128 +154,6 @@ fn channels_method_compiled_out(method: &str) -> bool { || method.starts_with("openhuman.webview_notifications_") } -#[test] -fn quoted_value_extracts_single_quoted_string() { - assert_eq!(quoted_value(": 'hello'"), "hello"); -} - -#[test] -fn quoted_value_extracts_double_quoted_string() { - assert_eq!(quoted_value(": \"hello\""), "hello"); -} - -#[test] -#[should_panic(expected = "expected quoted value")] -fn quoted_value_panics_on_unquoted_text() { - let _ = quoted_value(": bare-token"); -} - -#[test] -#[should_panic(expected = "unterminated quoted value")] -fn quoted_value_panics_on_unterminated_quote() { - let _ = quoted_value(": 'open-but-never-closed"); -} - -#[test] -fn object_body_after_marker_returns_inner_body() { - let source = "noise\nexport const FOO = {\n alpha: 'a',\n beta: 'b',\n} as const;\nrest"; - let body = object_body_after_marker(source, "export const FOO", "} as const;"); - assert!(body.contains("alpha: 'a'")); - assert!(body.contains("beta: 'b'")); - assert!(!body.contains("rest")); - assert!(!body.contains("noise")); -} - -#[test] -#[should_panic(expected = "missing marker")] -fn object_body_after_marker_panics_when_marker_absent() { - let _ = object_body_after_marker("nothing here", "export const MISSING", "};"); -} - -#[test] -#[should_panic(expected = "missing terminator")] -fn object_body_after_marker_panics_when_terminator_absent() { - let _ = object_body_after_marker( - "export const FOO = { alpha: 'a',", - "export const FOO", - "} as const;", - ); -} - -#[test] -fn parse_core_rpc_methods_extracts_entries_and_skips_comments() { - let source = "export const CORE_RPC_METHODS = {\n // a comment that should be skipped\n alphaMethod: 'openhuman.alpha',\n betaMethod: 'openhuman.beta',\n} as const;\n"; - let methods = parse_core_rpc_methods(source); - assert_eq!( - methods.get("alphaMethod").map(String::as_str), - Some("openhuman.alpha") - ); - assert_eq!( - methods.get("betaMethod").map(String::as_str), - Some("openhuman.beta") - ); - assert_eq!(methods.len(), 2); -} - -#[test] -#[should_panic(expected = "malformed CORE_RPC_METHODS entry")] -fn parse_core_rpc_methods_panics_on_non_colon_line() { - let source = - "export const CORE_RPC_METHODS = {\n alphaMethod 'openhuman.alpha',\n} as const;\n"; - let _ = parse_core_rpc_methods(source); -} - -#[test] -fn parse_frontend_legacy_aliases_resolves_core_method_refs_and_literals() { - let source = "export const CORE_RPC_METHODS = {\n alphaMethod: 'openhuman.alpha',\n} as const;\n\nexport const LEGACY_METHOD_ALIASES: Record = {\n 'openhuman.legacy_alpha': CORE_RPC_METHODS.alphaMethod,\n 'openhuman.legacy_literal': 'openhuman.literal_target',\n};\n"; - let core_methods = parse_core_rpc_methods(source); - let aliases = parse_frontend_legacy_aliases(source, &core_methods); - assert_eq!( - aliases.get("openhuman.legacy_alpha").map(String::as_str), - Some("openhuman.alpha") - ); - assert_eq!( - aliases.get("openhuman.legacy_literal").map(String::as_str), - Some("openhuman.literal_target") - ); -} - -#[test] -fn parse_frontend_legacy_aliases_accepts_bare_identifier_keys_and_skips_comments() { - // Prettier strips redundant quotes from keys that are valid JS - // identifiers, so the canonical form for a simple key like - // `health_snapshot` is unquoted. The parser must accept both - // `'foo':` and bare `foo:`, and must ignore `//` comment lines - // in the LEGACY_METHOD_ALIASES body. - let source = "export const CORE_RPC_METHODS = {\n alphaMethod: 'openhuman.alpha',\n betaMethod: 'openhuman.beta',\n} as const;\n\nexport const LEGACY_METHOD_ALIASES: Record = {\n // legacy aliases for the alpha method\n 'openhuman.legacy_alpha': CORE_RPC_METHODS.alphaMethod,\n beta_legacy: CORE_RPC_METHODS.betaMethod,\n};\n"; - let core_methods = parse_core_rpc_methods(source); - let aliases = parse_frontend_legacy_aliases(source, &core_methods); - assert_eq!( - aliases.get("openhuman.legacy_alpha").map(String::as_str), - Some("openhuman.alpha"), - "quoted-key entry should still resolve" - ); - assert_eq!( - aliases.get("beta_legacy").map(String::as_str), - Some("openhuman.beta"), - "bare-identifier key should resolve (Prettier-normalized form)" - ); - assert!( - !aliases - .keys() - .any(|k| k.contains("//") || k.contains("legacy aliases")), - "comment text must not be captured as a key" - ); -} - -#[test] -#[should_panic(expected = "legacy alias references unknown CORE_RPC_METHODS")] -fn parse_frontend_legacy_aliases_panics_on_unknown_core_method_ref() { - let source = "export const CORE_RPC_METHODS = {\n alphaMethod: 'openhuman.alpha',\n} as const;\n\nexport const LEGACY_METHOD_ALIASES: Record = {\n 'openhuman.legacy_alpha': CORE_RPC_METHODS.doesNotExist,\n};\n"; - let core_methods = parse_core_rpc_methods(source); - let _ = parse_frontend_legacy_aliases(source, &core_methods); -} - #[test] fn resolve_legacy_rewrites_every_table_entry() { for (legacy, canonical) in LEGACY_ALIASES { diff --git a/crates/openhuman-core/src/core/subsystem/schemas_tests.rs b/crates/openhuman-core/src/core/subsystem/schemas_tests.rs index 7a1ce5d7d54..3568451a087 100644 --- a/crates/openhuman-core/src/core/subsystem/schemas_tests.rs +++ b/crates/openhuman-core/src/core/subsystem/schemas_tests.rs @@ -10,11 +10,6 @@ fn status_schema_shape() { assert_eq!(schema.outputs[0].name, "subsystems"); } -#[test] -fn unknown_function_returns_the_unknown_schema() { - assert_eq!(schemas("not_real").function, "unknown"); -} - #[test] fn schemas_and_controllers_line_up() { let schemas = all_controller_schemas(); diff --git a/crates/openhuman-core/src/core/types_tests.rs b/crates/openhuman-core/src/core/types_tests.rs index e13b18ee08f..b411d0a5f5a 100644 --- a/crates/openhuman-core/src/core/types_tests.rs +++ b/crates/openhuman-core/src/core/types_tests.rs @@ -81,27 +81,6 @@ fn both_controller_return_paths_apply_the_same_log_envelope() { } } -#[test] -fn command_response_serde_roundtrip() { - let resp = CommandResponse { - result: "ok".to_string(), - logs: vec!["log1".into()], - }; - let json = serde_json::to_string(&resp).unwrap(); - let back: CommandResponse = serde_json::from_str(&json).unwrap(); - assert_eq!(back.result, "ok"); - assert_eq!(back.logs.len(), 1); -} - -#[test] -fn app_state_clone() { - let state = AppState { - core_version: "0.1.0".into(), - }; - let cloned = state.clone(); - assert_eq!(cloned.core_version, "0.1.0"); -} - #[test] fn host_kind_tag_is_stable() { // Downstream consumers (event-bus subscribers, log shippers) key diff --git a/crates/openhuman-core/src/cron/schemas_tests.rs b/crates/openhuman-core/src/cron/schemas_tests.rs index e265a59dd8c..f8a685f9d2b 100644 --- a/crates/openhuman-core/src/cron/schemas_tests.rs +++ b/crates/openhuman-core/src/cron/schemas_tests.rs @@ -68,15 +68,6 @@ fn schemas_runs_limit_is_optional() { assert!(!limit.required); } -#[test] -fn schemas_unknown_function_returns_placeholder_with_error_output() { - // The `_other` branch is used when a caller requests a schema - // for a function that does not exist — it should not panic. - let s = schemas("does-not-exist"); - assert_eq!(s.function, "unknown"); - assert_eq!(s.outputs[0].name, "error"); -} - // ── registry helpers ──────────────────────────────────────────── #[test] @@ -106,17 +97,6 @@ fn all_controller_schemas_covers_every_supported_function() { ); } -#[test] -fn all_registered_controllers_has_handler_per_schema() { - let controllers = all_registered_controllers(); - assert_eq!(controllers.len(), 6); - let names: Vec<_> = controllers.iter().map(|c| c.schema.function).collect(); - assert_eq!( - names, - vec!["add", "list", "update", "remove", "run", "runs"] - ); -} - // ── read_required ─────────────────────────────────────────────── #[test] diff --git a/crates/openhuman-core/src/desktop/app_state/schemas_tests.rs b/crates/openhuman-core/src/desktop/app_state/schemas_tests.rs index a481de9f7f3..ef6ad9af187 100644 --- a/crates/openhuman-core/src/desktop/app_state/schemas_tests.rs +++ b/crates/openhuman-core/src/desktop/app_state/schemas_tests.rs @@ -30,13 +30,6 @@ fn update_local_state_schema() { } } -#[test] -fn unknown_function_returns_unknown() { - let s = app_state_schemas("nonexistent"); - assert_eq!(s.function, "unknown"); - assert_eq!(s.namespace, "app_state"); -} - #[test] fn schemas_and_controllers_match() { let s = all_app_state_controller_schemas(); diff --git a/crates/openhuman-core/src/desktop/control/ops.rs b/crates/openhuman-core/src/desktop/control/ops.rs index 7295c937538..99e0e2d7108 100644 --- a/crates/openhuman-core/src/desktop/control/ops.rs +++ b/crates/openhuman-core/src/desktop/control/ops.rs @@ -180,11 +180,24 @@ fn permission(data: &serde_json::Value, field: &str) -> String { .and_then(serde_json::Value::as_str) .unwrap_or("unknown"); match raw { - "granted" | "denied" | "not_required" => raw.to_owned(), + "granted" | "denied" | "not_required" | "unknown" => raw.to_owned(), _ => "unknown".to_owned(), } } +/// On platforms without a per-app permission model for the given kind (e.g. +/// Windows has no macOS-style Accessibility or Screen Recording toggle), +/// treat an `unknown` report from the module as `not_required` so the UI +/// does not show a misleading "Not determined" state or send the user to +/// a generic settings page that has no relevant toggle. +pub(super) fn normalize_permission_for_platform(state: &str, platform: &str) -> String { + if platform == "windows" && state == "unknown" { + "not_required".to_owned() + } else { + state.to_owned() + } +} + pub async fn status(config: &Config) -> DesktopStatus { status_with(config, supported(), || { crate::modules::desktop::permissions(config) @@ -222,8 +235,14 @@ where match permissions().await { Ok(response) if response.ok => { if let Some(data) = response.data.as_ref() { - result.accessibility = permission(data, "accessibility"); - result.screen_recording = permission(data, "screen_recording"); + result.accessibility = normalize_permission_for_platform( + &permission(data, "accessibility"), + result.platform, + ); + result.screen_recording = normalize_permission_for_platform( + &permission(data, "screen_recording"), + result.platform, + ); } result.module_state = "ready".to_owned(); } @@ -289,13 +308,17 @@ where } } }; - if permissions + let accessibility_state = permissions .data .as_ref() - .map(|data| permission(data, "accessibility")) - .as_deref() - != Some("granted") - { + .map(|data| { + normalize_permission_for_platform( + &permission(data, "accessibility"), + std::env::consts::OS, + ) + }) + .unwrap_or_else(|| "unknown".to_owned()); + if accessibility_state != "granted" && accessibility_state != "not_required" { return DesktopProbe { ok: false, app_count: None, diff --git a/crates/openhuman-core/src/desktop/control/ops_tests.rs b/crates/openhuman-core/src/desktop/control/ops_tests.rs index 35bdb7a5378..09aca84ee41 100644 --- a/crates/openhuman-core/src/desktop/control/ops_tests.rs +++ b/crates/openhuman-core/src/desktop/control/ops_tests.rs @@ -248,12 +248,77 @@ async fn probe_requires_accessibility_and_snapshot_before_listing_apps() { assert_eq!(module_error.reason.as_deref(), Some("App listing denied")); } +#[tokio::test] +async fn probe_passes_when_accessibility_is_not_required() { + use tinycomputer_bus::DesktopResponse; + + let dir = tempfile::tempdir().unwrap(); + let mut config = Config::default(); + config.workspace_dir = dir.path().to_path_buf(); + save(&config, true).unwrap(); + + // Simulates the Windows adapter returning "unknown" for accessibility, + // which the host normalizes to "not_required" on the windows platform. + // Since this test binary runs on the build host (not necessarily windows), + // we pass "not_required" directly to prove the probe accepts it. + let result = probe_with(&config, true, |member| async move { + Ok(DesktopResponse::ok( + member, + match member { + names::methods::PERMISSIONS => serde_json::json!({ + "accessibility":{"state":"not_required"}, + "screen_recording":{"state":"not_required"} + }), + names::methods::SNAPSHOT => serde_json::json!({"elements":[]}), + names::methods::LIST_APPS => { + serde_json::json!({"apps":[{"name":"Explorer"}]}) + } + _ => panic!("unexpected member"), + }, + )) + }) + .await; + assert!( + result.ok, + "probe should pass when accessibility is not_required" + ); + assert_eq!(result.app_count, Some(1)); + assert!(result.reason.is_none()); +} + #[test] fn permission_states_are_normalized() { let data = serde_json::json!({"accessibility":{"state":"granted"}, "screen_recording":{"state":"weird"}}); assert_eq!(permission(&data, "accessibility"), "granted"); assert_eq!(permission(&data, "screen_recording"), "unknown"); + // "unknown" is a recognized pass-through state (distinct from a missing field). + let unknown = serde_json::json!({"accessibility":{"state":"unknown"}}); + assert_eq!(permission(&unknown, "accessibility"), "unknown"); +} + +#[test] +fn windows_unknown_permissions_normalize_to_not_required() { + assert_eq!( + normalize_permission_for_platform("unknown", "windows"), + "not_required" + ); + assert_eq!( + normalize_permission_for_platform("unknown", "macos"), + "unknown" + ); + assert_eq!( + normalize_permission_for_platform("granted", "windows"), + "granted" + ); + assert_eq!( + normalize_permission_for_platform("denied", "windows"), + "denied" + ); + assert_eq!( + normalize_permission_for_platform("not_required", "windows"), + "not_required" + ); } #[test] diff --git a/crates/openhuman-core/src/desktop/control/tools.rs b/crates/openhuman-core/src/desktop/control/tools.rs index 191580b7453..1ee9baa0940 100644 --- a/crates/openhuman-core/src/desktop/control/tools.rs +++ b/crates/openhuman-core/src/desktop/control/tools.rs @@ -295,14 +295,17 @@ impl Tool for DesktopTool { } Err(error) => return Ok(ToolResult::error(error)), }; - let accessibility = permission + let accessibility_raw = permission .data .as_ref() .and_then(|data| data.get("accessibility")) .and_then(|value| value.get("state")) .and_then(Value::as_str) .unwrap_or("unknown"); + let accessibility = + super::ops::normalize_permission_for_platform(accessibility_raw, std::env::consts::OS); if accessibility != "granted" + && accessibility != "not_required" && !matches!( self.kind, DesktopToolKind::Apps | DesktopToolKind::Windows | DesktopToolKind::Launch diff --git a/crates/openhuman-core/src/desktop/notifications/bus_tests_2_tests.rs b/crates/openhuman-core/src/desktop/notifications/bus_tests_2_tests.rs index f31e7644512..60f9904e585 100644 --- a/crates/openhuman-core/src/desktop/notifications/bus_tests_2_tests.rs +++ b/crates/openhuman-core/src/desktop/notifications/bus_tests_2_tests.rs @@ -41,39 +41,6 @@ fn cron_failed_uses_failure_title() { assert_eq!(n.title, "Cron job failed"); } -#[test] -fn successful_webhook_is_silent() { - let ev = DomainEvent::WebhookProcessed { - tunnel_id: "t".into(), - skill_id: "s".into(), - method: "POST".into(), - path: "/p".into(), - correlation_id: "c".into(), - status_code: 200, - elapsed_ms: 5, - error: None, - }; - assert!(event_to_notification(&ev).is_none()); -} - -#[test] -fn failed_webhook_produces_system_notification() { - let ev = DomainEvent::WebhookProcessed { - tunnel_id: "t".into(), - skill_id: "skill-x".into(), - method: "POST".into(), - path: "/p".into(), - correlation_id: "c".into(), - status_code: 500, - elapsed_ms: 12, - error: Some("boom".into()), - }; - let n = event_to_notification(&ev).unwrap(); - assert_eq!(n.category, CoreNotificationCategory::System); - assert!(n.body.contains("skill-x")); - assert!(n.body.contains("boom")); -} - #[test] fn subagent_completed_produces_agents_notification() { let ev = DomainEvent::SubagentCompleted { diff --git a/crates/openhuman-core/src/desktop/notifications/schemas_tests.rs b/crates/openhuman-core/src/desktop/notifications/schemas_tests.rs index 013eab400d3..ed1df52d07a 100644 --- a/crates/openhuman-core/src/desktop/notifications/schemas_tests.rs +++ b/crates/openhuman-core/src/desktop/notifications/schemas_tests.rs @@ -136,9 +136,3 @@ fn schemas_and_registered_controllers_have_bidirectional_parity() { assert_eq!(schema_functions, handler_functions); } - -#[test] -fn schemas_unknown_returns_placeholder() { - let s = schemas("does-not-exist"); - assert_eq!(s.function, "unknown"); -} diff --git a/crates/openhuman-core/src/desktop/notifications/store_tests_2_tests.rs b/crates/openhuman-core/src/desktop/notifications/store_tests_2_tests.rs index 3f37fa89eba..db99f53eb33 100644 --- a/crates/openhuman-core/src/desktop/notifications/store_tests_2_tests.rs +++ b/crates/openhuman-core/src/desktop/notifications/store_tests_2_tests.rs @@ -79,30 +79,6 @@ fn provider_filter_works() { assert_eq!(gmail[0].provider, "gmail"); } -#[test] -fn insert_if_not_recent_skips_duplicate() { - let dir = TempDir::new().unwrap(); - let config = test_config(&dir); - let n = sample_notification("dup-a", "slack"); - assert!(insert_if_not_recent(&config, &n).unwrap()); - - let n2 = sample_notification("dup-b", "slack"); - assert!(!insert_if_not_recent(&config, &n2).unwrap()); -} - -#[test] -fn insert_if_not_recent_rejects_expired_window_only() { - let dir = TempDir::new().unwrap(); - let config = test_config(&dir); - - let mut old = sample_notification("old1", "slack"); - old.received_at = Utc::now() - chrono::Duration::seconds(120); - insert(&config, &old).unwrap(); - - let fresh_same_content = sample_notification("fresh1", "slack"); - assert!(insert_if_not_recent(&config, &fresh_same_content).unwrap()); -} - #[test] fn insert_if_not_recent_is_atomic_under_concurrent_calls() { let dir = TempDir::new().unwrap(); @@ -131,17 +107,6 @@ fn insert_if_not_recent_is_atomic_under_concurrent_calls() { assert_eq!(items.len(), 1); } -#[test] -fn exists_recent_rejects_expired_notification() { - let dir = TempDir::new().unwrap(); - let config = test_config(&dir); - let mut n = sample_notification("old1", "slack"); - n.received_at = Utc::now() - chrono::Duration::seconds(120); - insert(&config, &n).unwrap(); - - assert!(!exists_recent(&config, "slack", None, "Test notification", "Test body").unwrap()); -} - #[test] fn settings_roundtrip_defaults_and_upsert() { let dir = TempDir::new().unwrap(); @@ -170,37 +135,6 @@ fn settings_roundtrip_defaults_and_upsert() { assert!(!updated.route_to_orchestrator); } -#[test] -fn exists_recent_detects_with_and_without_account_id() { - let dir = TempDir::new().unwrap(); - let config = test_config(&dir); - - let mut n = sample_notification("acct-1", "slack"); - n.account_id = Some("acct-main".to_string()); - insert(&config, &n).unwrap(); - - assert!(exists_recent( - &config, - "slack", - Some("acct-main"), - "Test notification", - "Test body" - ) - .unwrap()); - assert!(!exists_recent( - &config, - "slack", - Some("acct-other"), - "Test notification", - "Test body" - ) - .unwrap()); - - let n_null = sample_notification("acct-null", "slack"); - insert(&config, &n_null).unwrap(); - assert!(exists_recent(&config, "slack", None, "Test notification", "Test body").unwrap()); -} - #[test] fn mark_dismissed_and_mark_acted_report_match_and_update_status() { let dir = TempDir::new().unwrap(); diff --git a/crates/openhuman-core/src/flows/memory_tools_tests.rs b/crates/openhuman-core/src/flows/memory_tools_tests.rs index f7ad1202b4e..71fa8b60067 100644 --- a/crates/openhuman-core/src/flows/memory_tools_tests.rs +++ b/crates/openhuman-core/src/flows/memory_tools_tests.rs @@ -1,56 +1,4 @@ use super::*; -use crate::security::AutonomyLevel; -use tempfile::TempDir; - -// Seeding still goes through the engine handle (`UnifiedMemory` above), -// but the value types are the CONTRACT's: `tinymemory_core` re-exports -// `tinymemory_api::types::{MemoryCategory, MemoryTaint}` verbatim -// (tinymemory#18 §A1 moved them onto the contract so a second engine could -// be bound without translating). Naming them at the contract keeps the -// alias honest and is one fewer reason this file holds the crate (#5560). -use crate::memory::api::types::{MemoryCategory as EngineCategory, MemoryTaint as EngineTaint}; - -// ── Why `UnifiedMemory` is still here, and what replacing it costs (#5560) -// -// This whole module is `#[cfg(test)]`, so the engine is not linked into a -// production build from this file; the crate survives #5560 as a -// dev-dependency and this is the kind of fixture that keeps it. What the -// fixture cannot do is move to the bound driver in a one-line swap, and -// there are two independent reasons worth recording before someone tries. -// -// 1. **The seam is a different trait.** `test_mem` hands back -// `Arc` (= `tinymemory_api::traits::Memory`), and -// `Arc` does not coerce to it: `MemoryProvider`'s -// supertrait is `MemoryCore`, which is a *different* trait with taint as -// an argument rather than a second method (see `provider/mandatory.rs`, -// which says so at the definition). Rebinding the fixture onto -// `memory::test_support::install_memory_driver_for_test` therefore rewrites -// every `mem.store_with_taint(..)` / `mem.get(..)` in this module, not -// just its two lines. -// 2. **The backend choice is load-bearing.** `FLOW_MEMORY_NAMESPACE_PREFIX`'s -// doc above turns on `UnifiedMemory::sanitize_namespace` disagreeing with -// `Memory::forget`'s raw `WHERE namespace = ?1`. A volatile stand-in such -// as `tinycortex::memory::store::InMemoryMemoryStore` implements the same -// `Memory` trait and would compile, but it does not reproduce that -// inconsistency — so it would quietly stop testing the property the -// prefix exists to satisfy. -// -// Every test below that touches `test_mem` is already `#[ignore]`d, and -// their ignore reason is the deeper problem: the tools resolve the *bound -// driver*, so a store seeded here is not the store they read. Making them -// coherent again is a fixture rewrite against the binding — a change worth -// making on its own, with the tests un-ignored so the result is verified, -// not folded into a dependency-shedding pass. - -fn test_security() -> Arc { - Arc::new(SecurityPolicy::default()) -} - -fn test_mem() -> (TempDir, Arc) { - let tmp = TempDir::new().unwrap(); - let mem = crate::memory::tool_memory::test_helpers::MockMemory::default(); - (tmp, Arc::new(mem)) -} // ── flow_namespace / FLOW_MEMORY_NAMESPACE_PREFIX ─────────────── // (relocated from `flows::mod` — see that module's re-export comment) @@ -77,152 +25,11 @@ fn recall_name_and_schema() { assert!(schema["properties"]["flow_id"].is_object()); assert!(schema["properties"]["scope"].is_object()); } - -#[tokio::test] -#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \ -the tool resolves the bound driver rather than being handed a memory handle"] -async fn recall_empty_returns_no_results() { - let (_tmp, _mem) = test_mem(); - let tool = FlowMemoryRecallTool::new(); - let result = tool - .execute(json!({"query": "anything", "flow_id": "f1"})) - .await - .unwrap(); - assert!(!result.is_error); - assert!(result.output().contains("No memories found")); -} - -#[tokio::test] -#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \ -the tool resolves the bound driver rather than being handed a memory handle"] -async fn store_then_recall_matches() { - let (_tmp, mem) = test_mem(); - mem.store_with_taint( - &flow_namespace("f1"), - "sent_item_42", - "Sent newsletter item 42 to subscribers", - EngineCategory::Core, - None, - EngineTaint::ExternalSync, - ) - .await - .unwrap(); - - let tool = FlowMemoryRecallTool::new(); - let result = tool - .execute(json!({"query": "newsletter item 42", "flow_id": "f1"})) - .await - .unwrap(); - assert!(!result.is_error); - assert!(result.output().contains("newsletter item 42") || result.output().contains("42")); - assert!(result.output().contains("Found 1")); -} - -#[tokio::test] -#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \ -the tool resolves the bound driver rather than being handed a memory handle"] -async fn scope_flow_isolates_to_own_namespace() { - let (_tmp, mem) = test_mem(); - mem.store_with_taint( - &flow_namespace("f1"), - "k", - "shared keyword hit", - EngineCategory::Core, - None, - EngineTaint::ExternalSync, - ) - .await - .unwrap(); - mem.store_with_taint( - &flow_namespace("f2"), - "k", - "shared keyword hit", - EngineCategory::Core, - None, - EngineTaint::ExternalSync, - ) - .await - .unwrap(); - - let tool = FlowMemoryRecallTool::new(); - let result = tool - .execute(json!({"query": "shared keyword", "flow_id": "f1", "scope": "flow"})) - .await - .unwrap(); - assert!(!result.is_error); - // Only f1's own entry, not f2's. - assert!(result.output().contains("Found 1")); -} - -#[tokio::test] -#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \ -the tool resolves the bound driver rather than being handed a memory handle"] -async fn scope_flows_crosses_namespaces() { - let (_tmp, mem) = test_mem(); - mem.store_with_taint( - &flow_namespace("f1"), - "k", - "shared keyword hit from f1", - EngineCategory::Core, - None, - EngineTaint::ExternalSync, - ) - .await - .unwrap(); - mem.store_with_taint( - &flow_namespace("f2"), - "k", - "shared keyword hit from f2", - EngineCategory::Core, - None, - EngineTaint::ExternalSync, - ) - .await - .unwrap(); - - let tool = FlowMemoryRecallTool::new(); - let result = tool - .execute(json!({"query": "shared keyword", "flow_id": "f1", "scope": "flows"})) - .await - .unwrap(); - assert!(!result.is_error); - // Both f1's and f2's namespaces are visible under scope="flows". - assert!(result.output().contains("Found 2")); -} - -// T-m5: a missing/invalid input param reports via `ToolResult::error` -// (an `Ok(..)` the model can read and react to in-turn), never -// `Err(anyhow!)` (a hard tool-invocation failure) — matching every other -// input-validation problem on this belt (see the scope/empty-value -// tests above, which already used this channel before the fix). -#[tokio::test] -#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \ -the tool resolves the bound driver rather than being handed a memory handle"] -async fn recall_missing_query_errs() { - let (_tmp, _mem) = test_mem(); - let tool = FlowMemoryRecallTool::new(); - let result = tool.execute(json!({"flow_id": "f1"})).await.unwrap(); - assert!(result.is_error); - assert!(result.output().contains("Missing 'query'")); -} - -#[tokio::test] -#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \ -the tool resolves the bound driver rather than being handed a memory handle"] -async fn recall_missing_flow_id_errs() { - let (_tmp, _mem) = test_mem(); - let tool = FlowMemoryRecallTool::new(); - let result = tool.execute(json!({"query": "anything"})).await.unwrap(); - assert!(result.is_error); - assert!(result.output().contains("Missing 'flow_id'")); -} - // ── FlowMemoryRememberTool ────────────────────────────────────── #[test] fn remember_name_and_schema() { - let (_tmp, _mem) = test_mem(); - let tool = FlowMemoryRememberTool::new(test_security()); + let tool = FlowMemoryRememberTool::new(Arc::new(SecurityPolicy::default())); assert_eq!(tool.name(), "flow_memory_remember"); let schema = tool.parameters_schema(); assert!(schema["properties"]["flow_id"].is_object()); @@ -233,238 +40,3 @@ fn remember_name_and_schema() { assert!(schema["properties"]["namespace"].is_null()); assert_eq!(tool.permission_level(), PermissionLevel::Write); } - -/// Helper: a trusted `TrustedAutomation { Workflow }` origin scoped to -/// `job_id`, the only source `flow_memory_remember` will act on since the -/// T-M2 fix. -fn trusted_workflow_origin(job_id: &str) -> AgentTurnOrigin { - AgentTurnOrigin::TrustedAutomation { - job_id: job_id.to_string(), - source: TrustedAutomationSource::Workflow { - require_approval: false, - }, - } -} - -#[tokio::test] -#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \ -the tool resolves the bound driver rather than being handed a memory handle"] -async fn remember_stores_with_external_sync_taint() { - let (_tmp, mem) = test_mem(); - let tool = FlowMemoryRememberTool::new(test_security()); - let result = turn_origin::with_origin( - trusted_workflow_origin("f1"), - tool.execute(json!({"flow_id": "f1", "key": "sent_item_42", "content": "Sent item 42"})), - ) - .await - .unwrap(); - assert!(!result.is_error); - - let entry = mem - .get(&flow_namespace("f1"), "sent_item_42") - .await - .unwrap() - .expect("entry should be stored"); - assert_eq!(entry.content, "Sent item 42"); - assert_eq!(entry.taint, EngineTaint::ExternalSync); -} - -#[tokio::test] -#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \ -the tool resolves the bound driver rather than being handed a memory handle"] -async fn remember_writes_only_to_own_flow_namespace() { - let (_tmp, mem) = test_mem(); - let tool = FlowMemoryRememberTool::new(test_security()); - turn_origin::with_origin( - trusted_workflow_origin("f1"), - tool.execute(json!({"flow_id": "f1", "key": "k", "content": "f1 content"})), - ) - .await - .unwrap(); - - // Never lands in another flow's namespace, the shared "flows" scope - // namespace, or global/user memory. - assert!(mem.get(&flow_namespace("f2"), "k").await.unwrap().is_none()); - assert!(mem.get("global", "k").await.unwrap().is_none()); - assert!(mem - .get("f1", "k") // raw flow_id, not the derived namespace - .await - .unwrap() - .is_none()); -} - -/// SECURITY (T-M2): the primary fix under test — a chat/orchestrator turn -/// (no trusted `Workflow` run origin) must be refused outright, never -/// routed to the model-supplied `flow_id`. This is the exact -/// prompt-injection scenario: an attacker-controlled chat turn calling -/// `flow_memory_remember` with another flow's id to poison its dedup -/// memory (e.g. mark an item as already-sent so a digest flow skips it -/// forever). -#[tokio::test] -#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \ -the tool resolves the bound driver rather than being handed a memory handle"] -async fn remember_refuses_outside_a_trusted_workflow_run() { - let (_tmp, mem) = test_mem(); - let tool = FlowMemoryRememberTool::new(test_security()); - - // No `turn_origin::with_origin` wrapper — this call has no trusted - // Workflow run origin, exactly like every chat/orchestrator turn. - let result = tool - .execute(json!({ - "flow_id": "digest-flow-victim", - "key": "sent_item_42", - "content": "Sent newsletter item 42 to subscribers" - })) - .await - .unwrap(); - - assert!(result.is_error); - assert!(result - .output() - .contains("only available inside a workflow run")); - // Nothing was written to the targeted namespace — or anywhere else. - assert!(mem - .get(&flow_namespace("digest-flow-victim"), "sent_item_42") - .await - .unwrap() - .is_none()); -} - -/// SECURITY (Fix 1): a running flow's own id — carried by the run's -/// `TrustedAutomation { Workflow }` origin — is authoritative. A -/// mismatched, model-supplied `flow_id` arg must be silently ignored, -/// never allowed to redirect the write into a different flow's -/// namespace. -#[tokio::test] -#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \ -the tool resolves the bound driver rather than being handed a memory handle"] -async fn remember_ignores_mismatched_flow_id_arg_inside_trusted_workflow_run() { - let (_tmp, mem) = test_mem(); - let tool = FlowMemoryRememberTool::new(test_security()); - - let origin = AgentTurnOrigin::TrustedAutomation { - job_id: "f-real".to_string(), - source: TrustedAutomationSource::Workflow { - require_approval: false, - }, - }; - let result = turn_origin::with_origin( - origin, - tool.execute(json!({ - "flow_id": "f-other", - "key": "sent_item_1", - "content": "Sent item 1" - })), - ) - .await - .unwrap(); - assert!(!result.is_error); - - // Landed in the trusted run's own namespace... - assert!(mem - .get(&flow_namespace("f-real"), "sent_item_1") - .await - .unwrap() - .is_some()); - // ...and NOT the mismatched, model-supplied namespace. - assert!(mem - .get(&flow_namespace("f-other"), "sent_item_1") - .await - .unwrap() - .is_none()); -} - -#[tokio::test] -#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \ -the tool resolves the bound driver rather than being handed a memory handle"] -async fn remember_blocked_in_readonly_autonomy() { - let (_tmp, mem) = test_mem(); - let readonly = Arc::new(SecurityPolicy { - autonomy: AutonomyLevel::ReadOnly, - ..SecurityPolicy::default() - }); - let tool = FlowMemoryRememberTool::new(readonly); - let result = tool - .execute(json!({"flow_id": "f1", "key": "k", "content": "blocked"})) - .await - .unwrap(); - assert!(result.is_error); - assert!(result.output().contains("read-only mode")); - assert!(mem.get(&flow_namespace("f1"), "k").await.unwrap().is_none()); -} - -#[tokio::test] -#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \ -the tool resolves the bound driver rather than being handed a memory handle"] -async fn remember_rejects_secret_like_content() { - let (_tmp, mem) = test_mem(); - let tool = FlowMemoryRememberTool::new(test_security()); - let result = turn_origin::with_origin( - trusted_workflow_origin("f1"), - tool.execute(json!({ - "flow_id": "f1", - "key": "api", - "content": "api_key=sk-123456789012345678901234567890" - })), - ) - .await - .unwrap(); - assert!(result.is_error); - assert!(result.output().contains("looks like a secret")); - assert!(mem - .get(&flow_namespace("f1"), "api") - .await - .unwrap() - .is_none()); -} - -/// Outside a trusted run, `flow_id` no longer matters — the T-M2 refusal -/// fires regardless of whether it was supplied. (Inside a trusted run the -/// arg is informational only and ignored either way — see -/// `remember_ignores_mismatched_flow_id_arg_inside_trusted_workflow_run`.) -#[tokio::test] -#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \ -the tool resolves the bound driver rather than being handed a memory handle"] -async fn remember_missing_flow_id_outside_trusted_run_is_refused() { - let (_tmp, _mem) = test_mem(); - let tool = FlowMemoryRememberTool::new(test_security()); - let result = tool - .execute(json!({"key": "k", "content": "c"})) - .await - .unwrap(); - assert!(result.is_error); - assert!(result - .output() - .contains("only available inside a workflow run")); -} - -// T-m5 (retained through the T-M2 merge): the missing-param checks run -// BEFORE the trusted-origin resolution, so they are still reachable outside -// a run and still assert the `ToolResult::error` channel rather than `Err`. -#[tokio::test] -#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \ -the tool resolves the bound driver rather than being handed a memory handle"] -async fn remember_missing_key_errs() { - let (_tmp, _mem) = test_mem(); - let tool = FlowMemoryRememberTool::new(test_security()); - let result = tool - .execute(json!({"flow_id": "f1", "content": "c"})) - .await - .unwrap(); - assert!(result.is_error); - assert!(result.output().contains("Missing 'key'")); -} - -#[tokio::test] -#[ignore = "needs a built tinymemory module (OPENHUMAN_MODULE_PATH) and its own process: \ -the tool resolves the bound driver rather than being handed a memory handle"] -async fn remember_missing_content_errs() { - let (_tmp, _mem) = test_mem(); - let tool = FlowMemoryRememberTool::new(test_security()); - let result = tool - .execute(json!({"flow_id": "f1", "key": "k"})) - .await - .unwrap(); - assert!(result.is_error); - assert!(result.output().contains("Missing 'content'")); -} diff --git a/crates/openhuman-core/src/flows/schemas_tests.rs b/crates/openhuman-core/src/flows/schemas_tests.rs index 00e6e6dd3a4..d8cdcf2cc90 100644 --- a/crates/openhuman-core/src/flows/schemas_tests.rs +++ b/crates/openhuman-core/src/flows/schemas_tests.rs @@ -95,54 +95,6 @@ fn all_controller_schemas_covers_every_supported_function() { ); } -#[test] -fn all_registered_controllers_has_handler_per_schema() { - let controllers = all_registered_controllers(); - assert_eq!(controllers.len(), 36); - let names: Vec<_> = controllers.iter().map(|c| c.schema.function).collect(); - assert_eq!( - names, - vec![ - "create", - "duplicate", - "validate", - "import", - "get", - "list", - "list_connections", - "update", - "delete", - "set_enabled", - "run", - "run_detached", - "resume", - "cancel_run", - "list_runs", - "list_all_runs", - "get_run", - "prune_runs", - "build", - "build_cancel", - "discover", - "list_suggestions", - "dismiss_suggestion", - "mark_suggestion_built", - "draft_create", - "draft_get", - "draft_update", - "draft_list", - "draft_delete", - "draft_promote", - "get_history", - "rollback", - "search_tool_catalog", - "get_tool_contract", - "required_connections", - "approval_manifest", - ] - ); -} - #[test] fn schemas_import_requires_graph_and_optional_format() { let s = schemas("import"); @@ -372,13 +324,6 @@ fn read_flow_stream_target_generates_request_id_when_absent() { assert_ne!(target.request_id, target.thread_id); } -#[test] -fn schemas_unknown_function_returns_placeholder() { - let s = schemas("does-not-exist"); - assert_eq!(s.function, "unknown"); - assert_eq!(s.outputs[0].name, "error"); -} - #[test] fn read_required_errors_when_missing() { let params = Map::new(); diff --git a/crates/openhuman-core/src/hosting/hosting_tests.rs b/crates/openhuman-core/src/hosting/hosting_tests.rs index 1e9a268f0a0..a40170f4ff4 100644 --- a/crates/openhuman-core/src/hosting/hosting_tests.rs +++ b/crates/openhuman-core/src/hosting/hosting_tests.rs @@ -120,27 +120,3 @@ fn only_the_tools_that_change_the_world_carry_an_external_effect() { ); } } - -#[test] -fn every_tool_schema_is_an_object_naming_its_required_arguments() { - let workspace = tempfile::tempdir().expect("tempdir"); - let config = config_with(workspace.path(), true, "token"); - let account = Account::from_config(&config) - .expect("resolution does not fail") - .expect("an account"); - - for tool in account.tools() { - let schema = tool.parameters_schema(); - assert_eq!(schema["type"], "object", "{}", tool.name()); - assert!( - schema["properties"].is_object(), - "{} has no properties", - tool.name() - ); - assert!( - !tool.description().is_empty(), - "{} has no description", - tool.name() - ); - } -} diff --git a/crates/openhuman-core/src/inference/embedding_host/schemas_tests.rs b/crates/openhuman-core/src/inference/embedding_host/schemas_tests.rs index ccadfdb3249..4969e730239 100644 --- a/crates/openhuman-core/src/inference/embedding_host/schemas_tests.rs +++ b/crates/openhuman-core/src/inference/embedding_host/schemas_tests.rs @@ -20,13 +20,6 @@ fn schemas_and_controllers_match() { } } -#[test] -fn unknown_function_returns_unknown() { - let s = schemas("bad"); - assert_eq!(s.function, "unknown"); - assert_eq!(s.namespace, "embeddings"); -} - #[tokio::test] async fn all_handlers_accept_empty_params_without_panic() { // Every handler should return a result (Ok or Err) when called with diff --git a/crates/openhuman-core/src/inference/host_runtime/schemas_tests.rs b/crates/openhuman-core/src/inference/host_runtime/schemas_tests.rs index ddf47a8f2bd..7fdd450ce42 100644 --- a/crates/openhuman-core/src/inference/host_runtime/schemas_tests.rs +++ b/crates/openhuman-core/src/inference/host_runtime/schemas_tests.rs @@ -1,16 +1,5 @@ use super::*; -#[test] -fn catalog_counts_match_and_nonempty() { - let s = all_controller_schemas(); - let h = all_registered_controllers(); - assert_eq!(s.len(), h.len()); - assert!( - s.len() >= 10, - "local inference should expose >=10 controller fns" - ); -} - #[test] fn all_schemas_use_inference_namespace_and_have_descriptions() { for s in all_controller_schemas() { @@ -20,13 +9,6 @@ fn all_schemas_use_inference_namespace_and_have_descriptions() { } } -#[test] -fn unknown_function_returns_unknown_schema() { - let s = schemas("no_such_fn"); - assert_eq!(s.function, "unknown"); - assert_eq!(s.namespace, "inference"); -} - #[test] fn every_registered_key_resolves_to_non_unknown_schema() { let keys = [ diff --git a/crates/openhuman-core/src/inference/tokenjuice/schemas_tests.rs b/crates/openhuman-core/src/inference/tokenjuice/schemas_tests.rs index 5d7625aa6ce..59af0c51f45 100644 --- a/crates/openhuman-core/src/inference/tokenjuice/schemas_tests.rs +++ b/crates/openhuman-core/src/inference/tokenjuice/schemas_tests.rs @@ -8,24 +8,6 @@ fn all_schemas_have_namespace() { } /* Module-backed behavior is covered by TinyJuice's loader E2E. */ -#[tokio::test] -#[ignore = "requires a built TinyJuice module"] -async fn detect_handler_classifies_json() { - let mut p = Map::new(); - p.insert( - "content".into(), - Value::String(r#"[{"a":1,"b":2},{"a":3,"b":4}]"#.into()), - ); - let out = handle_detect(p).await.unwrap(); - assert_eq!(out["kind"], "json"); -} - -#[tokio::test] -#[ignore = "requires a built TinyJuice module"] -async fn cache_stats_handler_returns_counts() { - let out = handle_cache_stats(Map::new()).await.unwrap(); - assert!(out["entries"].is_u64()); -} // ── #6088: `compress` must expose all five ContentHint fields ──────────────── diff --git a/crates/openhuman-core/src/inference/tokenjuice/tools_tests.rs b/crates/openhuman-core/src/inference/tokenjuice/tools_tests.rs index 9980b185677..fad606631bb 100644 --- a/crates/openhuman-core/src/inference/tokenjuice/tools_tests.rs +++ b/crates/openhuman-core/src/inference/tokenjuice/tools_tests.rs @@ -1,28 +1,4 @@ use super::*; -#[tokio::test] -#[ignore = "requires a built TinyJuice module"] -async fn retrieves_offloaded_original() { - let original = "ORIGINAL TOKENJUICE PAYLOAD ".repeat(20); - let hash = "module-fixture"; - let tool = TokenjuiceRetrieveTool::new(); - let res = tool.execute(json!({ "token": hash })).await.unwrap(); - assert!(!res.is_error); - assert_eq!(res.output(), original); -} - -#[tokio::test] -#[ignore = "requires a built TinyJuice module"] -async fn retrieves_line_range() { - let _original = "r0\nr1\nr2\nr3\nr4"; - let hash = "module-fixture"; - let tool = TokenjuiceRetrieveTool::new(); - let res = tool - .execute(json!({ "token": hash, "range": { "start": 1, "end": 3, "unit": "lines" } })) - .await - .unwrap(); - assert!(!res.is_error); - assert_eq!(res.output(), "r1\nr2"); -} #[tokio::test] async fn missing_token_is_error() { diff --git a/crates/openhuman-core/src/inference/tokenjuice/types_tests.rs b/crates/openhuman-core/src/inference/tokenjuice/types_tests.rs index 80d7f401f37..362c84c5ee6 100644 --- a/crates/openhuman-core/src/inference/tokenjuice/types_tests.rs +++ b/crates/openhuman-core/src/inference/tokenjuice/types_tests.rs @@ -34,16 +34,3 @@ fn content_hint_matches_the_module_wire_shape() { }) ); } - -#[test] -fn retrieve_range_uses_camel_case_wire_values() { - let range = RetrieveRange { - start: 2, - end: 5, - unit: RangeUnit::Lines, - }; - assert_eq!( - serde_json::to_value(range).expect("serialize range"), - serde_json::json!({ "start": 2, "end": 5, "unit": "lines" }) - ); -} diff --git a/crates/openhuman-core/src/integrations/composio/schemas_tests.rs b/crates/openhuman-core/src/integrations/composio/schemas_tests.rs index 331fd53fb39..c2271b6003b 100644 --- a/crates/openhuman-core/src/integrations/composio/schemas_tests.rs +++ b/crates/openhuman-core/src/integrations/composio/schemas_tests.rs @@ -1,14 +1,6 @@ use super::*; use serde_json::json; -#[test] -fn catalog_counts_match() { - let s = all_controller_schemas(); - let h = all_registered_controllers(); - assert_eq!(s.len(), h.len()); - assert!(s.len() >= 9); -} - #[test] fn all_schemas_use_composio_namespace_and_have_descriptions() { for s in all_controller_schemas() { @@ -57,14 +49,6 @@ fn list_capabilities_schema_has_matrix_output() { .any(|f| f.name == "capabilities" && f.required)); } -#[test] -fn unknown_function_returns_unknown_schema() { - let s = schemas("no_such_fn"); - assert_eq!(s.function, "unknown"); - assert_eq!(s.inputs.len(), 1); - assert_eq!(s.inputs[0].name, "function"); -} - #[test] fn authorize_schema_requires_toolkit() { let s = schemas("authorize"); diff --git a/crates/openhuman-core/src/integrations/task_sources/schemas_tests.rs b/crates/openhuman-core/src/integrations/task_sources/schemas_tests.rs index e6082cae3d5..1dd27f7b6d8 100644 --- a/crates/openhuman-core/src/integrations/task_sources/schemas_tests.rs +++ b/crates/openhuman-core/src/integrations/task_sources/schemas_tests.rs @@ -44,13 +44,6 @@ fn schemas_add_requires_provider_and_filter() { assert!(provider.required); } -#[test] -fn schemas_unknown_function_returns_placeholder() { - let s = schemas("nope"); - assert_eq!(s.function, "unknown"); - assert_eq!(s.outputs[0].name, "error"); -} - #[test] fn read_provider_parses_known_and_rejects_unknown() { let mut params = Map::new(); diff --git a/crates/openhuman-core/src/integrations/test_support_backend.rs b/crates/openhuman-core/src/integrations/test_support_backend.rs index 7c3bc9068bb..3ee3d623f70 100644 --- a/crates/openhuman-core/src/integrations/test_support_backend.rs +++ b/crates/openhuman-core/src/integrations/test_support_backend.rs @@ -736,7 +736,3 @@ pub async fn spawn_fake_integration_backend() -> FakeIntegrationBackend { state, } } - -#[cfg(test)] -#[path = "test_support_tests.rs"] -mod tests; diff --git a/crates/openhuman-core/src/integrations/test_support_tests.rs b/crates/openhuman-core/src/integrations/test_support_tests.rs deleted file mode 100644 index 3c0ca83b06f..00000000000 --- a/crates/openhuman-core/src/integrations/test_support_tests.rs +++ /dev/null @@ -1,188 +0,0 @@ -use super::*; - -async fn get_json(client: &reqwest::Client, url: String) -> Value { - client - .get(url) - .send() - .await - .expect("GET request") - .json::() - .await - .expect("GET json body") -} - -async fn post_json(client: &reqwest::Client, url: String, body: Value) -> Value { - client - .post(url) - .json(&body) - .send() - .await - .expect("POST request") - .json::() - .await - .expect("POST json body") -} - -#[test] -fn as_string_array_filters_non_strings_and_missing_keys() { - let value = json!({ - "searchQueries": ["alpha", 42, null, "beta"] - }); - assert_eq!( - as_string_array(&value, "searchQueries"), - vec!["alpha".to_string(), "beta".to_string()] - ); - assert!(as_string_array(&value, "missing").is_empty()); -} - -#[tokio::test] -async fn fake_backend_records_requests_and_applies_route_defaults() { - let backend = spawn_fake_integration_backend().await; - let client = reqwest::Client::new(); - - let results = get_json( - &client, - format!( - "{}/agent-integrations/apify/runs/run-123/results", - backend.base_url - ), - ) - .await; - assert_eq!(results["data"]["items"].as_array().unwrap().len(), 3); - assert_eq!(results["data"]["total"], json!(8)); - - let twilio = post_json( - &client, - format!("{}/agent-integrations/twilio/call", backend.base_url), - json!({}), - ) - .await; - assert_eq!(twilio["data"]["callSid"], json!("CA0000")); - - let requests = backend.requests(); - assert_eq!(requests.len(), 2); - assert_eq!( - requests[0].path, - "/agent-integrations/apify/runs/run-123/results?limit=3&offset=0" - ); - assert_eq!(requests[1].body, json!({})); -} - -#[tokio::test] -async fn fake_backend_exercises_optional_and_fallback_response_paths() { - let backend = spawn_fake_integration_backend().await; - let client = reqwest::Client::new(); - - let apify = post_json( - &client, - format!("{}/agent-integrations/apify/run", backend.base_url), - json!({ - "actorId": "demo/actor", - "input": { "hello": "world" }, - "sync": false - }), - ) - .await; - assert_eq!(apify["data"]["status"], json!("RUNNING")); - assert_eq!(apify["data"]["datasetId"], json!("dataset-demo-actor")); - - let extract = post_json( - &client, - format!("{}/agent-integrations/parallel/extract", backend.base_url), - json!({ - "urls": ["https://example.com/a"] - }), - ) - .await; - assert_eq!(extract["data"]["results"][0]["full_content"], Value::Null); - assert_eq!( - extract["data"]["results"][0]["excerpts"][0], - json!("Focused on ") - ); - - let options = post_json( - &client, - format!( - "{}/agent-integrations/financial-apis/options", - backend.base_url - ), - json!({ - "symbol": "MSFT" - }), - ) - .await; - assert_eq!(options["data"]["symbol"], json!("MSFT")); - assert_eq!(options["data"]["contracts"][0]["delta"], Value::Null); - - let search = post_json( - &client, - format!("{}/agent-integrations/parallel/search", backend.base_url), - json!({ - "objective": "fallback objective" - }), - ) - .await; - assert_eq!(search["data"]["searchId"], json!("search-0")); - assert_eq!(search["data"]["results"], json!([])); - - let tinyfish = post_json( - &client, - format!("{}/agent-integrations/tinyfish/agent/run", backend.base_url), - json!({ - "url": "https://example.com", - "goal": "Return JSON" - }), - ) - .await; - assert_eq!(tinyfish["data"]["status"], json!("COMPLETED")); - assert_eq!(tinyfish["data"]["result"]["ok"], json!(true)); -} - -#[tokio::test] -async fn fake_backend_caps_google_results_and_echoes_dynamic_inputs() { - let backend = spawn_fake_integration_backend().await; - let client = reqwest::Client::new(); - - let places = post_json( - &client, - format!( - "{}/agent-integrations/google-places/search", - backend.base_url - ), - json!({ - "query": "pizza", - "maxResults": 9 - }), - ) - .await; - assert_eq!(places["data"]["results"].as_array().unwrap().len(), 3); - assert_eq!( - places["data"]["results"][2]["name"], - json!("pizza Result 3") - ); - - let commodity = post_json( - &client, - format!( - "{}/agent-integrations/financial-apis/commodity", - backend.base_url - ), - json!({ - "commodity": "BRENT" - }), - ) - .await; - assert_eq!(commodity["data"]["series"]["interval"], json!("daily")); - - let exchange = post_json( - &client, - format!( - "{}/agent-integrations/financial-apis/exchange-rate", - backend.base_url - ), - json!({}), - ) - .await; - assert_eq!(exchange["data"]["rate"]["fromCurrency"], json!("BTC")); - assert_eq!(exchange["data"]["rate"]["toCurrency"], json!("USD")); -} diff --git a/crates/openhuman-core/src/mcp/registry/schemas_tests.rs b/crates/openhuman-core/src/mcp/registry/schemas_tests.rs index d736752f2e3..3e5ba81d601 100644 --- a/crates/openhuman-core/src/mcp/registry/schemas_tests.rs +++ b/crates/openhuman-core/src/mcp/registry/schemas_tests.rs @@ -60,13 +60,6 @@ fn schemas_tool_call_requires_three_fields() { assert_eq!(required.len(), 3); } -#[test] -fn schemas_unknown_function_returns_placeholder() { - let s = schemas("not-a-real-function"); - assert_eq!(s.function, "unknown"); - assert_eq!(s.outputs[0].name, "error"); -} - // ── all_controller_schemas / all_registered_controllers ──────────────────── #[test] @@ -93,12 +86,6 @@ fn all_controller_schemas_covers_expected_methods() { assert!(functions.contains(&"oauth_begin")); } -#[test] -fn all_registered_controllers_has_handler_per_schema() { - let controllers = all_registered_controllers(); - assert_eq!(controllers.len(), 17); -} - #[test] fn all_registered_controllers_use_expected_namespaces() { for c in all_registered_controllers() { diff --git a/crates/openhuman-core/src/media/generation/README.md b/crates/openhuman-core/src/media/generation/README.md index 98a30c7e410..1d20cdcaa81 100644 --- a/crates/openhuman-core/src/media/generation/README.md +++ b/crates/openhuman-core/src/media/generation/README.md @@ -40,7 +40,7 @@ agent's tool list; it returns an empty list rather than erroring when no backend transport is installed, so a library host with no TinyHumans connection simply has no media tools rather than a broken one. Generated files land under `/generated-media/`, and `MediaArtifactTool` -moves each one into the workspace's `artifacts//` layout so it shows up +moves each one into the visible files folder (`~/OpenHuman/projects/Files`, metadata in the workspace's `artifacts//`) so it shows up as a card in the chat UI. Billing and margin stay backend-side: this module never charges directly, it only refuses to submit when `crate::integrations::client::budget_gate` reports the account's managed diff --git a/crates/openhuman-core/src/media/generation/artifact_tool.rs b/crates/openhuman-core/src/media/generation/artifact_tool.rs index 2071fb5d2db..37bb1a11e68 100644 --- a/crates/openhuman-core/src/media/generation/artifact_tool.rs +++ b/crates/openhuman-core/src/media/generation/artifact_tool.rs @@ -50,18 +50,26 @@ pub struct MediaArtifactTool { inner: T, kind: ArtifactKind, workspace_dir: PathBuf, + /// Visible folder each generated file is moved into (#5505). + files_dir: crate::agent::artifacts::FileRoots, } impl MediaArtifactTool { /// `kind` is the artifact category to file every generated output /// under (`ArtifactKind::Image` / `ArtifactKind::Video`); `workspace_dir` - /// is the same workspace root the rest of the artifacts module writes - /// `/artifacts//...` under. - pub fn new(inner: T, kind: ArtifactKind, workspace_dir: impl Into) -> Self { + /// holds the artifact metadata; `files_dir` is the visible folder the + /// generated file is moved into (#5505). + pub fn new( + inner: T, + kind: ArtifactKind, + workspace_dir: impl Into, + files_dir: impl Into, + ) -> Self { Self { inner, kind, workspace_dir: workspace_dir.into(), + files_dir: files_dir.into(), } } @@ -134,6 +142,7 @@ impl MediaArtifactTool { let title = Self::artifact_title(args, index, total); let (meta, dest) = match create_artifact_for_call( &self.workspace_dir, + &self.files_dir, self.kind.clone(), &title, &ext, @@ -161,13 +170,14 @@ impl MediaArtifactTool { } } Err(err) => { - let _ = fail_artifact(&self.workspace_dir, &meta.id, &err).await; + let _ = fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &err) + .await; set_artifact_error(entry, &err); } } } Err(err) => { - let _ = fail_artifact(&self.workspace_dir, &meta.id, &err).await; + let _ = fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &err).await; tracing::warn!( target: "media_generation", err = %err, @@ -187,7 +197,7 @@ fn set_artifact_error(entry: &mut Value, message: &str) { } /// Moves `src` to `dest`, falling back to copy + remove across filesystem -/// boundaries (`rename` fails with `EXDEV` when the artifacts root and the +/// boundaries (`rename` fails with `EXDEV` when the files folder and the /// media output dir are on different mounts). Returns the final file size. async fn move_or_copy(src: &Path, dest: &Path) -> Result { if tokio::fs::rename(src, dest).await.is_err() { diff --git a/crates/openhuman-core/src/media/generation/artifact_tool_tests.rs b/crates/openhuman-core/src/media/generation/artifact_tool_tests.rs index eab9fcb7064..fc15401a301 100644 --- a/crates/openhuman-core/src/media/generation/artifact_tool_tests.rs +++ b/crates/openhuman-core/src/media/generation/artifact_tool_tests.rs @@ -79,6 +79,7 @@ async fn files_a_single_generated_artifact() { }, ArtifactKind::Image, workspace.clone(), + root.path().join("Files"), ); let result = wrapped @@ -115,6 +116,7 @@ async fn files_every_artifact_when_n_greater_than_one() { }, ArtifactKind::Image, workspace.clone(), + root.path().join("Files"), ); let result = wrapped @@ -148,6 +150,7 @@ async fn leaves_an_errored_tool_result_untouched() { }, ArtifactKind::Image, workspace.clone(), + root.path().join("Files"), ); let result = wrapped.execute(json!({ "prompt": "x" })).await.unwrap(); @@ -166,7 +169,8 @@ async fn host_metadata_forwards_to_the_inner_tool() { fail: false, }, ArtifactKind::Video, - workspace, + workspace.clone(), + workspace.join("Files"), ); assert_eq!(wrapped.name(), "stub_generate"); assert_eq!(wrapped.permission_level(), PermissionLevel::ReadOnly); diff --git a/crates/openhuman-core/src/media/generation/tools.rs b/crates/openhuman-core/src/media/generation/tools.rs index 022cf3a5d79..12e293ad20a 100644 --- a/crates/openhuman-core/src/media/generation/tools.rs +++ b/crates/openhuman-core/src/media/generation/tools.rs @@ -54,6 +54,7 @@ pub fn build_media_tools(root_config: &Config, action_dir: &Path) -> Vec, video_wait: WaitPolicy, ) -> Vec> { + let files = files_dir.into(); let MediaGenerators { image, video } = generators; let output = MediaOutput::new(action_dir) .with_reference_policy(reference_policy(action_dir, workspace_dir)); @@ -79,6 +82,7 @@ pub fn media_tools_from( .with_category(ToolCategory::Workflow), ArtifactKind::Image, workspace_dir.to_path_buf(), + files.clone(), )), Box::new(MediaArtifactTool::new( GenerateVideoTool::new(Arc::clone(&video), output) @@ -89,6 +93,7 @@ pub fn media_tools_from( .with_wait_policy(video_wait), ArtifactKind::Video, workspace_dir.to_path_buf(), + files, )), Box::new(MediaListModelsTool { image, video }), ]; diff --git a/crates/openhuman-core/src/media/generation/tools_tests.rs b/crates/openhuman-core/src/media/generation/tools_tests.rs index cf08ebbd285..4e46914564e 100644 --- a/crates/openhuman-core/src/media/generation/tools_tests.rs +++ b/crates/openhuman-core/src/media/generation/tools_tests.rs @@ -19,6 +19,7 @@ fn tools(action_dir: &Path) -> Vec> { }, action_dir, &action_dir.join("workspace"), + &action_dir.join("Files"), tinyagents_harness::tinyinference_video::WaitPolicy::new( std::time::Duration::from_millis(1), std::time::Duration::from_secs(5), @@ -109,63 +110,6 @@ fn schemas_expose_the_reference_standards() { } } -#[tokio::test] -async fn image_tool_files_each_generated_file_as_an_artifact() { - // The `media_generate_image` tool is wrapped in a `MediaArtifactTool` - // (`super::artifact_tool`) which relocates every file the inner - // `GenerateImageTool` writes under `/generated-media/` into - // the artifact store under `/artifacts//` and tags - // the result entry with `artifact_id`, so nothing is left behind in - // `generated-media` and the artifact directory holds the file instead. - let dir = tempfile::tempdir().unwrap(); - let tools = tools(dir.path()); - let result = by_name(&tools, IMAGE_TOOL_NAME) - .execute(json!({ "prompt": "an anime comic about a delivery certificate" })) - .await - .unwrap(); - assert!(!result.is_error, "{result:?}"); - - let payload = result - .content - .iter() - .find_map(|block| match block { - tinytools::ToolContent::Json { data } => Some(data.clone()), - _ => None, - }) - .expect("json content block"); - let artifacts = payload["artifacts"].as_array().expect("artifacts array"); - assert_eq!(artifacts.len(), 1); - let artifact_id = artifacts[0]["artifact_id"] - .as_str() - .expect("artifact_id set on the entry"); - assert!( - artifacts[0].get("artifact_error").is_none(), - "{:?}", - artifacts[0] - ); - - // Nothing left behind in the raw generated-media staging dir... - let staged = std::fs::read_dir(dir.path().join("generated-media")) - .unwrap() - .count(); - assert_eq!(staged, 0, "generated file should have been moved"); - - // ...and the file now lives under the artifact store, alongside the - // `meta.json` record `create_artifact_for_call` writes. - let workspace = dir.path().join("workspace"); - let artifact_dir = workspace.join("artifacts").join(artifact_id); - let entries: Vec = std::fs::read_dir(&artifact_dir) - .unwrap() - .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) - .collect(); - assert!(entries.contains(&"meta.json".to_string()), "{entries:?}"); - assert_eq!( - entries.len(), - 2, - "expected meta.json + the moved media file under {artifact_dir:?}, got {entries:?}" - ); -} - #[tokio::test] async fn list_models_reports_both_catalogs_and_defaults() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/openhuman-core/src/memory/auto_recall/auto_recall_tests.rs b/crates/openhuman-core/src/memory/auto_recall/auto_recall_tests.rs index 5364d9d6c61..f9d6f3decc8 100644 --- a/crates/openhuman-core/src/memory/auto_recall/auto_recall_tests.rs +++ b/crates/openhuman-core/src/memory/auto_recall/auto_recall_tests.rs @@ -511,6 +511,27 @@ async fn from_guard_asks_the_notes_namespace_through_the_retrieval_family() { ); } +/// Hosted CortexDB's retrieval family ranks its notes and reports no signal: +/// they are kept in the engine's order, as an unscored engine's are, rather +/// than all dropped by the similarity floor. +#[tokio::test] +async fn from_guard_keeps_a_rank_only_drivers_notes_in_its_order() { + let ranked = |key: &str, content: &str, rank: f64| { + let mut hit = namespace_hit("global", key, content, 0.0); + hit.score = rank; + hit.score_breakdown.final_score = rank; + hit + }; + let provider = RecordingProvider::new().with_namespace_hits(vec![ + ranked("favourite_tea_oolong", TEA_NOTE, 1.0), + ranked("rent", "Rent is due on the 5th.", 0.9), + ]); + let (_provider, guard) = guarded_with(provider, embedded_policy()); + let lane = AutoRecall::from_guard(Arc::new(guard)); + let block = lane.block_for(TEA_QUESTION).await.expect("a block"); + assert!(block.contains(TEA_NOTE), "{block}"); +} + #[tokio::test] async fn from_guard_honours_the_hooks_switch() { let hooks = crate::config::schema::MemoryHooksConfig { diff --git a/crates/openhuman-core/src/memory/auto_recall/source.rs b/crates/openhuman-core/src/memory/auto_recall/source.rs index 3782cfd97d5..1b318a908a6 100644 --- a/crates/openhuman-core/src/memory/auto_recall/source.rs +++ b/crates/openhuman-core/src/memory/auto_recall/source.rs @@ -50,9 +50,10 @@ pub struct ScoredNotes { /// The hits, most relevant first. pub hits: Vec, /// Whether each hit's `vector_similarity` is the engine's own score. - /// `false` for an engine whose recall is ranked but carries no score - /// (hosted CortexDB): its hits read 0.0, and flooring on that would drop - /// every one of them however well the engine ranked it. + /// `false` for an engine whose recall is ranked but carries no similarity + /// (hosted CortexDB, with or without its retrieval family): its hits read + /// 0.0, and flooring on that would drop every one of them however well + /// the engine ranked it. pub scored: bool, } @@ -129,9 +130,18 @@ impl AutoRecallSource for GuardSource { // No session to exclude: the notes namespace is never auto-saved per // session, and the lane runs before this turn is archived, so there is // no self-echo for the engine's exclusion to catch. - retrieval + let hits = retrieval .recall_namespace_scored(namespace, query, limit, None) - .await - .map(ScoredNotes::scored) + .await?; + // A retrieval family can rank without measuring similarity (hosted + // CortexDB scores by rank): its hits are unscored notes, not misses. + let scored = !crate::memory::ops::fallback::rank_only(&hits); + if !scored { + log::debug!( + "[auto_recall] retrieval ranks without similarity; notes kept in rank order hits={}", + hits.len() + ); + } + Ok(ScoredNotes { hits, scored }) } } diff --git a/crates/openhuman-core/src/memory/display_name_and_vault_rpc_tests.rs b/crates/openhuman-core/src/memory/display_name_and_vault_rpc_tests.rs index 03810f706ce..306eef188f6 100644 --- a/crates/openhuman-core/src/memory/display_name_and_vault_rpc_tests.rs +++ b/crates/openhuman-core/src/memory/display_name_and_vault_rpc_tests.rs @@ -9,12 +9,25 @@ async fn read_chunk_row_returns_none_for_missing_chunk() { } #[test] -fn display_name_unslugs_email_thread_with_user_hint() { - let name = display_name_for_source( - "gmail:alice@example.com|bob@example.com", - Some("alice@example.com"), - ); - assert_eq!(name, "bob@example.com"); +fn display_name_unslugs_sources_for_display() { + // (source id, user hint, expected display name) + let cases = [ + ( + "gmail:alice@example.com|bob@example.com", + Some("alice@example.com"), + "bob@example.com", + ), + ("slack:#engineering", None, "#engineering"), + ( + "gmail:Alice@Example.com|bob@example.com|carol@example.com", + Some(" alice@example.com "), + "bob@example.com, carol@example.com", + ), + ("loose-id", None, "loose-id"), + ]; + for (source, hint, expected) in cases { + assert_eq!(display_name_for_source(source, hint), expected, "{source}"); + } } #[test] @@ -25,28 +38,6 @@ fn display_name_falls_back_to_arrow_when_user_unknown() { assert!(name.contains("↔")); } -#[test] -fn display_name_strips_platform_prefix() { - assert_eq!( - display_name_for_source("slack:#engineering", None), - "#engineering" - ); -} - -#[test] -fn display_name_handles_multiple_participants_and_trimmed_hint() { - let name = display_name_for_source( - "gmail:Alice@Example.com|bob@example.com|carol@example.com", - Some(" alice@example.com "), - ); - assert_eq!(name, "bob@example.com, carol@example.com"); -} - -#[test] -fn display_name_handles_no_prefix() { - assert_eq!(display_name_for_source("loose-id", None), "loose-id"); -} - #[test] fn sanitize_basename_replaces_windows_illegal_characters() { assert_eq!( diff --git a/crates/openhuman-core/src/memory/driver/README.md b/crates/openhuman-core/src/memory/driver/README.md index 7ecbd6e242f..f5a975e23cd 100644 --- a/crates/openhuman-core/src/memory/driver/README.md +++ b/crates/openhuman-core/src/memory/driver/README.md @@ -47,19 +47,32 @@ and publishes `MemoryDriverChanged`. ### What degrades on a remote engine The remote engines advertise the three mandatory families plus what their -dialect adds (CortexDB and TinyHumans: document/conversation/learning/event -ingest and `answer`; Mem0: conversation ingest and graph; Cognee: graph). The -module-only surfaces (`documents`, `tree`, `sources`, `entities`, `people`, -`maintenance`, `goals`, `tool_memory`) are absent from those engines. Their RPCs +dialect adds: + +- **CortexDB and TinyHumans:** document, conversation, learning and event + ingest, and `answer`. +- **TinyHumans alone:** `goals`, `tool_memory`, `documents`, `sources`, + `maintenance`, `retrieval`, `ingest`, `profile`, `episodic`, `scoring` and + `tree` too (tinymemory's hosted-families spec). +- **Mem0:** conversation ingest and graph. +- **Cognee:** graph. + +The other module-only surfaces are absent from those engines: `chunks`, +`entities`, `people`, `source_sync`, `coding_sessions`, and on every remote +engine but TinyHumans the families above. For an engine with a sink and no +`source_sync` (TinyHumans), the host syncs local sources itself +(`memory/sources/hosted_sync.rs`). Their RPCs are capability-gated out of the registry when a context is ambient, and answer "memory driver does not support the ... family" otherwise. `provider_status`, the engine RPCs and the mandatory core/recall RPCs are never gated. -Two host lanes read the mandatory recall on such an engine, and an engine that -ranks without scoring (hosted CortexDB) changes what they can do. Auto-recall's -notes leg keeps the engine's first `AUTO_RECALL_UNSCORED_NOTES` hits instead of -flooring similarities that all read 0.0 (`memory/auto_recall`), and a refused -lookup puts its reason in the block (`auto_recall/refusal.rs`). Situational +Two host lanes read namespace recall, and an engine that ranks without scoring +(hosted CortexDB) changes what they can do, whether it answers through the +mandatory recall or its retrieval family (whose hits carry a rank and no +signal: `memory/ops/fallback.rs::rank_only`). Auto-recall's notes leg keeps the +engine's first `AUTO_RECALL_UNSCORED_NOTES` hits instead of flooring +similarities that all read 0.0 (`memory/auto_recall`), and a refused lookup +puts its reason in the block (`auto_recall/refusal.rs`). Situational preferences and the contradiction check (`memory/preferences`) cannot judge relevance without a score and answer nothing. A connector sync resolves the Sources sink before it asks the connector for pages, because the connector diff --git a/crates/openhuman-core/src/memory/ops/engine.rs b/crates/openhuman-core/src/memory/ops/engine.rs index 96d116041aa..c4223938f8e 100644 --- a/crates/openhuman-core/src/memory/ops/engine.rs +++ b/crates/openhuman-core/src/memory/ops/engine.rs @@ -133,13 +133,33 @@ fn expected_capabilities(id: &str) -> Vec { } "mem0" => &[C::ConversationIngest, C::Graph], "cognee" => &[C::Graph], - "cortex" | "tinyhumans" => &[ + "cortex" => &[ C::DocumentIngest, C::ConversationIngest, C::LearningIngest, C::EventIngest, C::Answer, ], + // The direct wire's families, plus the ones only the hosted wire serves + // (tinymemory `docs/specs/tinyhumans-hosted-families.md`). + "tinyhumans" => &[ + C::DocumentIngest, + C::ConversationIngest, + C::LearningIngest, + C::EventIngest, + C::Answer, + C::Goals, + C::ToolMemory, + C::Documents, + C::Sources, + C::Maintenance, + C::Retrieval, + C::Ingest, + C::Profile, + C::Episodic, + C::Scoring, + C::Tree, + ], _ => &[], }; caps.extend(extra.iter().map(|c| c.as_str())); @@ -295,21 +315,29 @@ pub fn classify_engine_message(message: &str) -> String { { return message.to_string(); } + // The backend's billing code is a verdict on this account wherever it is + // quoted, and saying so signs no one out. if message.contains("USER_INSUFFICIENT_CREDITS") { return format!("{INSUFFICIENT_CREDITS_PREFIX} the memory engine is out of credits"); } // Only the error's own class decides, never a class quoted in its detail. let class = memory_error_class(message); - let forbidden = match class { - Some((class, detail)) => class == "unauthorized: " && is_forbidden(detail), - // No class tag: a bare adapter message, whose first status is its own. - None => is_forbidden(message), + // An auth refusal of the error's own: its class is `unauthorized: `, or it + // has no class tag (a bare adapter message, whose first status is its own). + let own_auth_detail = match class { + Some(("unauthorized: ", detail)) => Some(detail), + Some(_) => None, + None => Some(message), }; - if forbidden { + if own_auth_detail.is_some_and(is_forbidden) { return format!("{MEMORY_FORBIDDEN_PREFIX} the memory engine refused this credential"); } + // A lapsed session signs the user out, so the hosted `[UNAUTHORIZED]` + // code counts only as the error's own: quoted by an outage (the backend + // relaying its upstream's 401 as a 503, say) it is not this user's + // session. OpenHuman's own `SESSION_EXPIRED:` marker counts wherever it is. if message.contains(SESSION_EXPIRED_PREFIX) - || message.contains("[UNAUTHORIZED]") + || (own_auth_detail.is_some() && message.contains("[UNAUTHORIZED]")) || (message.starts_with("unauthorized:") && message.contains("re-authenticate")) { return format!("{SESSION_EXPIRED_PREFIX} no TinyHumans session"); diff --git a/crates/openhuman-core/src/memory/ops/engine_tests.rs b/crates/openhuman-core/src/memory/ops/engine_tests.rs index 5a667671daf..83d90a3ceac 100644 --- a/crates/openhuman-core/src/memory/ops/engine_tests.rs +++ b/crates/openhuman-core/src/memory/ops/engine_tests.rs @@ -61,6 +61,62 @@ fn every_remote_engine_is_listed_with_at_least_the_mandatory_families() { assert!(hosted.hosted); assert!(!hosted.needs_key); assert!(hosted.capabilities.iter().any(|c| c == "answer")); + // The families only the hosted wire serves (tinymemory + // `docs/specs/tinyhumans-hosted-families.md`); a direct CortexDB has none. + for family in [ + "goals", + "tool_memory", + "documents", + "sources", + "maintenance", + "retrieval", + "ingest", + "profile", + "episodic", + "scoring", + "tree", + ] { + assert!( + hosted.capabilities.iter().any(|c| c == family), + "tinyhumans must advertise {family}: {:?}", + hosted.capabilities + ); + if let Some(direct) = engines.iter().find(|e| e.id == "cortex") { + assert!( + !direct.capabilities.iter().any(|c| c == family), + "cortex must not advertise {family}: {:?}", + direct.capabilities + ); + } + } +} + +/// The hosted row mirrors what the hosted driver advertises when it binds: the +/// UI offers a family only when the driver serves it. Hosted memory keeps no +/// local chunk store, which is what keeps the local-engine controls hidden. +#[cfg(feature = "memory-remote")] +#[test] +fn the_hosted_row_mirrors_what_the_hosted_driver_advertises() { + use tinymemory::factory::{build_provider, EngineConfig, EngineCredential}; + let provider = build_provider( + "tinyhumans", + &EngineConfig { + endpoint: Some("http://127.0.0.1:9".to_string()), + deployment: None, + }, + EngineCredential::Static("tiny_live_test".to_string()), + ) + .expect("the hosted driver builds without a request"); + let mut advertised: Vec = provider + .capabilities() + .iter() + .map(|c| c.as_str().to_string()) + .collect(); + let mut row = expected_capabilities("tinyhumans"); + advertised.sort(); + row.sort(); + assert_eq!(row, advertised); + assert!(!row.iter().any(|c| c == "chunks"), "{row:?}"); } #[test] @@ -239,6 +295,36 @@ fn a_class_quoted_in_another_errors_detail_does_not_decide_it() { ); } +#[test] +fn an_auth_code_quoted_by_another_class_does_not_sign_the_user_out() { + // The backend relaying its own upstream's 401 as a 503 is an outage, not + // this user's lapsed session. + for outage in [ + "unavailable: upstream returned [UNAUTHORIZED]", + "unavailable: [UNAUTHORIZED] memory API memory/recall on host (HTTP 503 Service \ + Unavailable): memory service token rejected", + ] { + let classified = classify_engine_message(outage); + assert!( + classified.starts_with(MEMORY_UNREACHABLE_PREFIX), + "{outage} -> {classified}" + ); + } + let invalid = "invalid input: upstream said [UNAUTHORIZED]"; + assert_eq!(classify_engine_message(invalid), invalid); + // Two markers count wherever they are quoted: OpenHuman's own + // `SESSION_EXPIRED:` (the session is gone, whatever wrapped that) and the + // backend's billing code (a verdict on this account). + let session = classify_engine_message("backend failed: SESSION_EXPIRED: no TinyHumans session"); + assert!(session.starts_with(SESSION_EXPIRED_PREFIX), "{session}"); + let credits = + classify_engine_message("backend failed: [USER_INSUFFICIENT_CREDITS] out of credits"); + assert!( + credits.starts_with(INSUFFICIENT_CREDITS_PREFIX), + "{credits}" + ); +} + #[test] fn an_engine_that_cannot_serve_now_is_unreachable() { for error in [ diff --git a/crates/openhuman-core/src/memory/ops/fallback.rs b/crates/openhuman-core/src/memory/ops/fallback.rs index d02477c3d82..4cde17b8106 100644 --- a/crates/openhuman-core/src/memory/ops/fallback.rs +++ b/crates/openhuman-core/src/memory/ops/fallback.rs @@ -65,7 +65,9 @@ pub(crate) fn classify_for_engine(external: bool, message: String) -> String { pub(crate) fn classify_rpc_error(message: String) -> String { let external = crate::core::runtime::context::CoreContext::current() .and_then(|ctx| ctx.memory().ok()) - .is_none_or(|guard| guard.policy().class() == crate::core::subsystem::DriverClass::External); + .is_none_or(|guard| { + guard.policy().class() == crate::core::subsystem::DriverClass::External + }); classify_for_engine(external, message) } @@ -128,6 +130,29 @@ pub(crate) async fn namespace_names(guard: &MemoryGuard) -> Result, Ok(summaries.into_iter().map(|s| s.namespace).collect()) } +/// Whether `hits` were ranked without anything measured: each has a positive +/// final score and no signal at all — no similarity, keyword, graph, episodic +/// or freshness. +/// +/// That is the mark a driver ranking without scoring leaves (hosted CortexDB's +/// retrieval family scores a hit by its rank and reports no signal), and a +/// weighted sum of signals cannot produce it, so an engine that scores is +/// never read as one. A similarity floor cannot tell such hits apart, so a +/// caller treats them as it treats [`ranked_recall`]'s unscored ones. An empty +/// list is not rank-only: there is nothing to keep either way. +pub(crate) fn rank_only(hits: &[NamespaceMemoryHit]) -> bool { + !hits.is_empty() + && hits.iter().all(|hit| { + let signals = &hit.score_breakdown; + signals.final_score > 0.0 + && signals.vector_similarity == 0.0 + && signals.keyword_relevance == 0.0 + && signals.graph_relevance == 0.0 + && signals.episodic_relevance == 0.0 + && signals.freshness == 0.0 + }) +} + /// What [`ranked_recall`] answered: the hits, and whether the engine scored /// them. pub(crate) struct RankedRecall { diff --git a/crates/openhuman-core/src/memory/ops/fallback_tests.rs b/crates/openhuman-core/src/memory/ops/fallback_tests.rs index 489576b5e9f..333275b21cf 100644 --- a/crates/openhuman-core/src/memory/ops/fallback_tests.rs +++ b/crates/openhuman-core/src/memory/ops/fallback_tests.rs @@ -218,3 +218,27 @@ fn error_envelopes_carry_the_classified_message() { let message = outcome.value.error.expect("error").message; assert!(message.starts_with("INSUFFICIENT_CREDITS:"), "{message}"); } + +/// A hit as a driver ranking without scoring sends it: a rank, no signal. +fn ranked_hit(key: &str, rank_score: f64) -> NamespaceMemoryHit { + let mut hit = crate::memory::guard::test_support::namespace_hit("global", key, key, 0.0); + hit.score = rank_score; + hit.score_breakdown.final_score = rank_score; + hit +} + +#[test] +fn a_ranking_with_no_signal_is_rank_only_and_a_scored_one_is_not() { + let ranked = vec![ranked_hit("a", 1.0), ranked_hit("b", 0.9)]; + assert!(rank_only(&ranked)); + assert!(!rank_only(&[]), "nothing is not a ranking"); + let mut keyword = ranked.clone(); + keyword[1].score_breakdown.keyword_relevance = 0.4; + assert!(!rank_only(&keyword), "one measured signal makes it scored"); + let mut recent = ranked.clone(); + recent[0].score_breakdown.freshness = 0.7; + assert!(!rank_only(&recent), "recency is a signal"); + let mut unranked = ranked; + unranked[0].score_breakdown.final_score = 0.0; + assert!(!rank_only(&unranked), "a zero final score is not a rank"); +} diff --git a/crates/openhuman-core/src/memory/ops/mod.rs b/crates/openhuman-core/src/memory/ops/mod.rs index 623dfc1c30c..a7caf94bef7 100644 --- a/crates/openhuman-core/src/memory/ops/mod.rs +++ b/crates/openhuman-core/src/memory/ops/mod.rs @@ -88,11 +88,10 @@ pub use tool_memory::{ // --------------------------------------------------------------------------- #[cfg(test)] -pub(crate) use envelope::{error_envelope, memory_counts, memory_request_id}; +pub(crate) use envelope::memory_request_id; #[cfg(test)] pub(crate) use helpers::{ - build_retrieval_context, chunk_metadata, default_category, default_priority, - default_source_type, extract_entity_type, filter_hits_by_document_ids, + build_retrieval_context, chunk_metadata, extract_entity_type, filter_hits_by_document_ids, format_llm_context_message, maybe_retrieval_context, relation_identity, relation_metadata, timestamp_to_rfc3339, validate_memory_relative_path, }; diff --git a/crates/openhuman-core/src/memory/ops_tests.rs b/crates/openhuman-core/src/memory/ops_tests.rs index 00cad0ce1ed..d68daa18ede 100644 --- a/crates/openhuman-core/src/memory/ops_tests.rs +++ b/crates/openhuman-core/src/memory/ops_tests.rs @@ -153,12 +153,10 @@ fn format_llm_context_message_includes_entity_types_when_present() { // ── Pure-helper coverage ─────────────────────────────────────── use super::{ - chunk_metadata, default_category, default_priority, default_source_type, error_envelope, - extract_entity_type, maybe_retrieval_context, memory_counts, memory_request_id, + chunk_metadata, extract_entity_type, maybe_retrieval_context, memory_request_id, relation_identity, relation_metadata, timestamp_to_rfc3339, validate_memory_relative_path, }; -use crate::core::Outcome; -use crate::memory::{ApiEnvelope, MemoryRetrievalContext}; +use crate::memory::MemoryRetrievalContext; #[test] fn memory_request_id_is_nonempty_and_unique() { @@ -169,20 +167,6 @@ fn memory_request_id_is_nonempty_and_unique() { assert_ne!(a, b); } -#[test] -fn memory_counts_builds_btreemap_from_entries() { - let m = memory_counts([("documents", 3), ("kv", 1)]); - assert_eq!(m.get("documents"), Some(&3)); - assert_eq!(m.get("kv"), Some(&1)); - assert_eq!(m.len(), 2); -} - -#[test] -fn memory_counts_is_empty_for_empty_input() { - let m: std::collections::BTreeMap = memory_counts(std::iter::empty()); - assert!(m.is_empty()); -} - #[test] fn timestamp_to_rfc3339_valid_seconds_and_fractional() { let s = timestamp_to_rfc3339(1_700_000_000.0).unwrap(); @@ -192,13 +176,6 @@ fn timestamp_to_rfc3339_valid_seconds_and_fractional() { assert!(s.contains("2023")); } -#[test] -fn timestamp_to_rfc3339_rejects_non_finite_and_negative() { - assert!(timestamp_to_rfc3339(f64::NAN).is_none()); - assert!(timestamp_to_rfc3339(f64::INFINITY).is_none()); - assert!(timestamp_to_rfc3339(-1.0).is_none()); -} - fn relation_fixture(namespace: Option<&str>) -> GraphRelationRecord { GraphRelationRecord { namespace: namespace.map(str::to_string), @@ -291,13 +268,6 @@ fn maybe_retrieval_context_respects_include_flag() { assert!(maybe_retrieval_context(true, ctx).is_some()); } -#[test] -fn default_constants_are_stable() { - assert!(!default_source_type().is_empty()); - assert!(!default_priority().is_empty()); - assert!(!default_category().is_empty()); -} - #[test] fn validate_memory_relative_path_rejects_empty_absolute_and_traversal() { // Empty string is now allowed: it refers to the memory root @@ -309,16 +279,3 @@ fn validate_memory_relative_path_rejects_empty_absolute_and_traversal() { assert!(validate_memory_relative_path("ok/subdir/file.md").is_ok()); assert!(validate_memory_relative_path("simple.txt").is_ok()); } - -#[test] -fn error_envelope_produces_api_error_with_code_and_message() { - let envelope: Outcome> = - error_envelope::("NOT_FOUND", "missing".into()); - let api = &envelope.value; - assert!(api.data.is_none()); - let err = api.error.as_ref().expect("error set"); - assert_eq!(err.code, "NOT_FOUND"); - assert_eq!(err.message, "missing"); - // Meta must carry a request id. - assert!(!api.meta.request_id.is_empty()); -} diff --git a/crates/openhuman-core/src/memory/preferences/mod.rs b/crates/openhuman-core/src/memory/preferences/mod.rs index ef1f4365c65..be290cb6267 100644 --- a/crates/openhuman-core/src/memory/preferences/mod.rs +++ b/crates/openhuman-core/src/memory/preferences/mod.rs @@ -92,9 +92,21 @@ pub(crate) async fn recall_by_vector_over( let started = std::time::Instant::now(); let hits = match provider.as_retrieval() { Some(retrieval) => { - retrieval + let hits = retrieval .recall_namespace_scored(namespace, query, limit, None) - .await? + .await?; + if crate::memory::ops::fallback::rank_only(&hits) { + // A retrieval family that ranks without measuring similarity + // (hosted CortexDB) is the unscored engine below under another + // name, and gets the same answer for the same reason. + log::debug!( + "[pref_recall] namespace={namespace} retrieval ranks without similarity; \ + nothing clears a similarity floor elapsed_ms={}", + started.elapsed().as_millis() + ); + return Ok(Vec::new()); + } + hits } // No retrieval family (a remote engine): the mandatory ranked recall // answers, so Lane B still works instead of injecting nothing. diff --git a/crates/openhuman-core/src/memory/preferences/preferences_tests.rs b/crates/openhuman-core/src/memory/preferences/preferences_tests.rs index f886a180400..d886f828e2e 100644 --- a/crates/openhuman-core/src/memory/preferences/preferences_tests.rs +++ b/crates/openhuman-core/src/memory/preferences/preferences_tests.rs @@ -330,6 +330,25 @@ async fn situational_recall_filters_on_the_vector_component_not_the_final_score( assert_eq!(out, vec!["Prefers vim.".to_string()]); } +/// A retrieval family that ranks without measuring any signal (hosted +/// CortexDB) is the unscored engine under another name: no floor can tell a +/// preference that fits from one that does not, so neither lane injects one. +#[tokio::test] +async fn a_driver_ranking_without_signals_yields_no_preferences() { + let guard = scripted(vec![ + ("editor", "Prefers vim.", 0.0), + ("tone", "Be terse.", 0.0), + ]); + assert!(recall_situational_preferences(&guard, "which editor?") + .await + .is_empty()); + assert!( + recall_related_preferences(&guard, "Be brief.", "verbosity", 4) + .await + .is_empty() + ); +} + #[tokio::test] async fn an_empty_query_recalls_nothing_without_asking_the_driver() { let guard = scripted(vec![("editor", "Prefers vim.", 0.99)]); diff --git a/crates/openhuman-core/src/memory/read_rpc/admin.rs b/crates/openhuman-core/src/memory/read_rpc/admin.rs index b31a1338955..c996f5ab143 100644 --- a/crates/openhuman-core/src/memory/read_rpc/admin.rs +++ b/crates/openhuman-core/src/memory/read_rpc/admin.rs @@ -540,6 +540,9 @@ pub async fn delete_source_rpc( }) .await .map_err(|e| format!("delete_source: {e}"))?; + // A host-synced source's record of what it sent would otherwise skip the + // items just forgotten on its next sync. + crate::memory::sources::hosted_sync::forget_state(config, &source_id); let resp = DeleteSourceResponse { // `deleted` is true if we removed chunks OR cleaned a stale orphaned diff --git a/crates/openhuman-core/src/memory/read_rpc/graph.rs b/crates/openhuman-core/src/memory/read_rpc/graph.rs index 33314f7e2d8..5a860485226 100644 --- a/crates/openhuman-core/src/memory/read_rpc/graph.rs +++ b/crates/openhuman-core/src/memory/read_rpc/graph.rs @@ -76,6 +76,15 @@ pub struct GraphExportResponse { /// still the cut the UI sees. const CHUNK_LABEL_CHARS: usize = 72; +/// Label cap for a summary node whose driver serves its text inline — hosted +/// memory's concepts, beliefs and facts. The same cut as a chunk's, so the two +/// read alike on the canvas. +const SUMMARY_LABEL_CHARS: usize = CHUNK_LABEL_CHARS; + +/// The tree kind a hosted driver reports for the forest it draws from the +/// server's own understanding. +const HOSTED_TREE_KIND: &str = "understanding"; + // ── graph_export ──────────────────────────────────────────────────────── pub async fn graph_export_rpc( @@ -172,6 +181,9 @@ async fn collect_tree_graph(cfg: &Config) -> Result<(Vec, Vec = + leaves.iter().map(|leaf| leaf.chunk_id.clone()).collect(); + nodes = drop_stand_ins(nodes, &leaf_ids); for leaf in leaves { let TreeLeaf { chunk_id, @@ -247,10 +259,18 @@ fn shape_summary_nodes(summaries: Vec, max_nodes: usize) -> Vec (text.chars().take(SUMMARY_LABEL_CHARS).collect(), None), + None => ( + format!("L{level} · {tree_scope}"), + Some(sanitize_basename(&id)), + ), + }; SummaryRow { node: GraphNode { kind: "summary".into(), @@ -266,7 +286,7 @@ fn shape_summary_nodes(summaries: Vec, max_nodes: usize) -> Vec, max_nodes: usize) -> Vec = std::collections::BTreeSet::new(); + // Scope to the kind of tree that occupies it. A hosted driver's trees are + // its namespaces and read as what they hold; every other driver's scope is + // shown as it names itself. + let mut scopes: std::collections::BTreeMap = std::collections::BTreeMap::new(); for sr in &summary_rows { - scopes.insert(sr.tree_scope.clone()); + scopes + .entry(sr.tree_scope.clone()) + .or_insert_with(|| sr.node.tree_kind.clone().unwrap_or_default()); } let mut nodes: Vec = Vec::new(); let mut source_root_ids: std::collections::HashMap = std::collections::HashMap::new(); - for scope in &scopes { + for (scope, tree_kind) in &scopes { let root_id = format!("source:{scope}"); - let label = scope_display_label(scope); + let label = scope_display_label(scope, tree_kind); source_root_ids.insert(scope.clone(), root_id.clone()); nodes.push(GraphNode { kind: "source".into(), @@ -367,7 +392,46 @@ fn shape_summary_nodes(summaries: Vec, max_nodes: usize) -> Vec String { +/// Drops the document leaves that stand in for children the leaf listing +/// then returned as leaves of their own. +/// +/// A document leaf is drawn for each child of an L1 summary so a child the +/// listing never returns still shows. One the listing does return would be +/// drawn twice — once as the stand-in, once as itself — so its stand-in goes. +pub(super) fn drop_stand_ins( + nodes: Vec, + leaf_ids: &std::collections::HashSet, +) -> Vec { + nodes + .into_iter() + .filter(|node| { + let stands_in_for = node.tree_scope.as_deref().and_then(|scope| { + node.id + .strip_prefix("doc:") + .and_then(|rest| rest.strip_prefix(scope)) + .and_then(|rest| rest.strip_prefix(':')) + }); + !(node.kind == "chunk" && stands_in_for.is_some_and(|child| leaf_ids.contains(child))) + }) + .collect() +} + +/// The name a source root carries: a hosted driver's namespaces read as what +/// they hold, and every other scope reads as it names itself. +/// +/// `tree_kind` is what keeps the two apart. The embedded engine has a `global` +/// tree of its own, whose scope is the literal `global`, so matching on the +/// scope alone would rename a node that has nothing to do with hosted memory. +pub(super) fn scope_display_label(scope: &str, tree_kind: &str) -> String { + if tree_kind == HOSTED_TREE_KIND { + match scope { + "global" => return "Memory".to_string(), + "sources/chat" => return "Chat".to_string(), + "sources/email" => return "Email".to_string(), + "sources/documents" => return "Documents".to_string(), + _ => {} + } + } if scope.starts_with("github:") { let repo = scope.strip_prefix("github:").unwrap_or(scope); format!("GitHub · {repo}") diff --git a/crates/openhuman-core/src/memory/read_rpc/graph_tests.rs b/crates/openhuman-core/src/memory/read_rpc/graph_tests.rs index 5a329164697..2d2f3b2714f 100644 --- a/crates/openhuman-core/src/memory/read_rpc/graph_tests.rs +++ b/crates/openhuman-core/src/memory/read_rpc/graph_tests.rs @@ -24,10 +24,15 @@ //! 4. **The node budget cuts the document tail, never the summaries.** The //! summaries are the skeleton — a budget that dropped them would leave //! document leaves parented to nodes that are not in the response. +//! 5. **A summary served with its text is labelled by it, and has no file.** +//! Hosted memory's concepts, beliefs and facts live on the server; a path +//! into the local content vault would open nothing. +//! 6. **A child is drawn once.** A document leaf stands in for a child the leaf +//! listing does not return, and goes when the listing returns it. use chrono::{TimeZone, Utc}; -use super::shape_summary_nodes; +use super::{drop_stand_ins, scope_display_label, shape_summary_nodes}; use crate::memory::api::tree::TreeSummary; const BUDGET: usize = 10_000; @@ -49,6 +54,7 @@ fn summary( child_ids: children.iter().map(|c| (*c).to_string()).collect(), time_range_start: Utc.timestamp_opt(1_700_000_000, 0).unwrap(), time_range_end: Utc.timestamp_opt(1_700_000_900, 0).unwrap(), + preview: None, } } @@ -243,3 +249,74 @@ fn an_empty_forest_shapes_to_no_nodes_at_all() { // root per scope it has never seen. assert!(shape_summary_nodes(Vec::new(), BUDGET).is_empty()); } + +#[test] +fn a_summary_served_with_its_text_is_labelled_by_it_and_has_no_file() { + let mut concept = summary("concept_job", "sources/email", 3, None, &["belief_1"]); + concept.preview = Some(format!("Alice's new job — {}", "detail ".repeat(20))); + let nodes = shape_summary_nodes( + vec![concept, summary("s1", "sources/email", 1, None, &[])], + BUDGET, + ); + let node = |id: &str| nodes.iter().find(|n| n.id == id).expect("node"); + let concept = node("concept_job"); + assert!(concept.label.starts_with("Alice's new job — ")); + assert_eq!(concept.label.chars().count(), super::SUMMARY_LABEL_CHARS); + assert_eq!(concept.file_basename, None, "no vault file to open"); + let sealed = node("s1"); + assert_eq!(sealed.label, "L1 · sources/email"); + assert!(sealed.file_basename.is_some()); +} + +#[test] +fn a_child_the_leaf_listing_returns_is_drawn_once() { + let nodes = shape_summary_nodes( + vec![summary( + "fact_1", + "sources/email", + 1, + None, + &["evt_1", "evt_2"], + )], + BUDGET, + ); + let leaves: std::collections::HashSet = ["evt_1".to_string()].into(); + let kept = drop_stand_ins(nodes, &leaves); + let ids: Vec<&str> = kept.iter().map(|n| n.id.as_str()).collect(); + assert!( + ids.contains(&"doc:sources/email:evt_2"), + "an unlisted child keeps its stand-in" + ); + assert!( + !ids.contains(&"doc:sources/email:evt_1"), + "a listed child is drawn as itself" + ); + assert!(ids.contains(&"fact_1") && ids.contains(&"source:sources/email")); +} + +#[test] +fn hosted_namespaces_read_as_what_they_hold() { + let hosted = "understanding"; + assert_eq!(scope_display_label("global", hosted), "Memory"); + assert_eq!(scope_display_label("sources/chat", hosted), "Chat"); + assert_eq!(scope_display_label("sources/email", hosted), "Email"); + assert_eq!( + scope_display_label("sources/documents", hosted), + "Documents" + ); + assert_eq!(scope_display_label("slack:#eng", hosted), "Slack · #eng"); +} + +/// The embedded engine has a `global` tree of its own; renaming it would be a +/// change to a mode this work does not touch. +#[test] +fn another_drivers_scopes_are_left_alone() { + for kind in ["global", "source", "topic"] { + assert_eq!(scope_display_label("global", kind), "global"); + assert_eq!(scope_display_label("sources/email", kind), "sources/email"); + } + assert_eq!( + scope_display_label("gmail:a-at-b-dot-com", "source"), + "Gmail · a@b.com" + ); +} diff --git a/crates/openhuman-core/src/memory/schemas/documents_tests.rs b/crates/openhuman-core/src/memory/schemas/documents_tests.rs index 8e483850087..dbeca523be1 100644 --- a/crates/openhuman-core/src/memory/schemas/documents_tests.rs +++ b/crates/openhuman-core/src/memory/schemas/documents_tests.rs @@ -30,11 +30,6 @@ fn capability_partitions_are_disjoint_and_total() { } } -#[test] -fn unknown_document_schema_returns_none() { - assert!(schema("not_real").is_none()); -} - #[test] fn query_namespace_schema_requires_namespace_and_query() { let schema = schema("query_namespace").unwrap(); diff --git a/crates/openhuman-core/src/memory/schemas/files_tests.rs b/crates/openhuman-core/src/memory/schemas/files_tests.rs index 1f378c4d903..3a3663a328b 100644 --- a/crates/openhuman-core/src/memory/schemas/files_tests.rs +++ b/crates/openhuman-core/src/memory/schemas/files_tests.rs @@ -6,11 +6,6 @@ fn file_schema_exposes_all_functions() { assert_eq!(controllers().len(), FUNCTIONS.len()); } -#[test] -fn unknown_file_schema_returns_none() { - assert!(schema("not_real").is_none()); -} - #[test] fn write_file_schema_requires_path_and_content() { let schema = schema("write_file").unwrap(); diff --git a/crates/openhuman-core/src/memory/schemas/kv_graph_tests.rs b/crates/openhuman-core/src/memory/schemas/kv_graph_tests.rs index 187859ffa8c..cd35a1d8635 100644 --- a/crates/openhuman-core/src/memory/schemas/kv_graph_tests.rs +++ b/crates/openhuman-core/src/memory/schemas/kv_graph_tests.rs @@ -16,11 +16,6 @@ fn kv_graph_schema_exposes_all_functions() { assert_eq!(controllers().len(), FUNCTIONS.len()); } -#[test] -fn unknown_kv_graph_schema_returns_none() { - assert!(schema("not_real").is_none()); -} - #[test] fn graph_upsert_schema_requires_subject_predicate_and_object() { let schema = schema("graph_upsert").unwrap(); diff --git a/crates/openhuman-core/src/memory/schemas/learn_tests.rs b/crates/openhuman-core/src/memory/schemas/learn_tests.rs index 15d51198532..57f3ae517ea 100644 --- a/crates/openhuman-core/src/memory/schemas/learn_tests.rs +++ b/crates/openhuman-core/src/memory/schemas/learn_tests.rs @@ -6,11 +6,6 @@ fn learn_schema_only_exposes_learn_all() { assert_eq!(controllers().len(), 1); } -#[test] -fn unknown_learn_schema_returns_none() { - assert!(schema("not_real").is_none()); -} - #[test] fn learn_all_schema_has_optional_namespaces_input() { let schema = schema("learn_all").unwrap(); diff --git a/crates/openhuman-core/src/memory/schemas/provider_tests.rs b/crates/openhuman-core/src/memory/schemas/provider_tests.rs index a2192ac9139..d078f8a52ef 100644 --- a/crates/openhuman-core/src/memory/schemas/provider_tests.rs +++ b/crates/openhuman-core/src/memory/schemas/provider_tests.rs @@ -20,11 +20,6 @@ fn provider_family_exposes_status_and_the_engine_selector() { } } -#[test] -fn unknown_provider_schema_returns_none() { - assert!(schema("not_real").is_none()); -} - #[test] fn provider_status_schema_has_no_inputs_and_names_the_status_fields() { let schema = schema("provider_status").unwrap(); diff --git a/crates/openhuman-core/src/memory/schemas/sync_tests.rs b/crates/openhuman-core/src/memory/schemas/sync_tests.rs index 8f15f29f873..43365fdcd2e 100644 --- a/crates/openhuman-core/src/memory/schemas/sync_tests.rs +++ b/crates/openhuman-core/src/memory/schemas/sync_tests.rs @@ -14,11 +14,6 @@ fn sync_schema_exposes_all_functions() { assert_eq!(controllers().len(), FUNCTIONS.len()); } -#[test] -fn unknown_sync_schema_returns_none() { - assert!(schema("not_real").is_none()); -} - #[test] fn sync_channel_schema_requires_channel_id() { let schema = schema("sync_channel").unwrap(); diff --git a/crates/openhuman-core/src/memory/schemas/tool_memory_tests.rs b/crates/openhuman-core/src/memory/schemas/tool_memory_tests.rs index eb028a91c40..c333da5ea87 100644 --- a/crates/openhuman-core/src/memory/schemas/tool_memory_tests.rs +++ b/crates/openhuman-core/src/memory/schemas/tool_memory_tests.rs @@ -23,11 +23,6 @@ fn controllers_match_function_count() { assert!(registered.iter().all(|c| c.schema.namespace == "memory")); } -#[test] -fn schema_returns_none_for_unknown_function() { - assert!(schema("not_real").is_none()); -} - #[test] fn tool_rule_put_schema_requires_tool_name_and_rule() { let schema = schema("tool_rule_put").unwrap(); diff --git a/crates/openhuman-core/src/memory/schemas_tests.rs b/crates/openhuman-core/src/memory/schemas_tests.rs index 222df909aff..c333da26a50 100644 --- a/crates/openhuman-core/src/memory/schemas_tests.rs +++ b/crates/openhuman-core/src/memory/schemas_tests.rs @@ -262,28 +262,6 @@ fn each_family_pairs_its_schemas_with_its_controllers() { ); } -#[test] -fn all_controller_schemas_has_entry_per_supported_function() { - let names: Vec<_> = all_controller_schemas() - .into_iter() - .map(|s| s.function) - .collect(); - assert_eq!(names.len(), ALL_FUNCTIONS.len()); - for expected in ALL_FUNCTIONS { - assert!(names.contains(expected), "missing schema for {expected}"); - } -} - -#[test] -fn all_registered_controllers_has_handler_per_schema() { - let controllers = all_registered_controllers(); - assert_eq!(controllers.len(), ALL_FUNCTIONS.len()); - let names: Vec<_> = controllers.iter().map(|c| c.schema.function).collect(); - for expected in ALL_FUNCTIONS { - assert!(names.contains(expected), "missing handler for {expected}"); - } -} - #[test] fn every_schema_uses_memory_namespace() { for s in all_controller_schemas() { @@ -345,36 +323,9 @@ fn parse_params_surfaces_deserialization_errors_with_context() { // ── sync / learn schema shape tests ───────────────────────────────────── -#[test] -fn sync_channel_schema_requires_channel_id() { - let s = schemas("sync_channel"); - assert_eq!(s.namespace, "memory"); - assert_eq!(s.function, "sync_channel"); - let required: Vec<_> = s - .inputs - .iter() - .filter(|f| f.required) - .map(|f| f.name) - .collect(); - assert!( - required.contains(&"channel_id"), - "channel_id must be required" - ); -} - #[test] fn sync_all_schema_has_no_inputs() { let s = schemas("sync_all"); assert_eq!(s.function, "sync_all"); assert!(s.inputs.is_empty(), "sync_all takes no inputs"); } - -#[test] -fn learn_all_schema_namespaces_is_optional() { - let s = schemas("learn_all"); - assert_eq!(s.function, "learn_all"); - assert_eq!(s.inputs.len(), 1); - let ns_field = &s.inputs[0]; - assert_eq!(ns_field.name, "namespaces"); - assert!(!ns_field.required, "namespaces must be optional"); -} diff --git a/crates/openhuman-core/src/memory/source_scope_tests.rs b/crates/openhuman-core/src/memory/source_scope_tests.rs index 62127074dbf..ae3946dd607 100644 --- a/crates/openhuman-core/src/memory/source_scope_tests.rs +++ b/crates/openhuman-core/src/memory/source_scope_tests.rs @@ -87,3 +87,51 @@ async fn chunk_gate_empty_allowlist_blocks_tagged_sources_only() { }) .await; } + +// `as_bus_scope` renders the task-local scope for the memory module's bus +// argument. `None` means unrestricted; `Some(empty)` denies every +// source-attributed item. Collapsing one onto the other inverts the policy. + +#[tokio::test] +async fn unrestricted_recall_renders_as_no_scope_not_an_empty_allowlist() { + assert!(as_bus_scope().is_none()); + + with_source_scope(None, async { + assert!(as_bus_scope().is_none()); + }) + .await; +} + +#[tokio::test] +async fn an_empty_allowlist_renders_as_a_scope_that_denies_every_source() { + with_source_scope(Some(vec![]), async { + let scope = as_bus_scope().expect("an empty allowlist is a restriction"); + assert!(scope.is_empty()); + assert!(!scope.allows_source_id("mem_src:anything:item-1")); + }) + .await; +} + +#[tokio::test] +async fn the_allowlist_crosses_the_bus_and_matches_by_the_drivers_rule() { + let allowed = vec!["gmail:work".to_string(), "src-abc".to_string()]; + + with_source_scope(Some(allowed.clone()), async { + let scope = as_bus_scope().expect("a non-empty allowlist must render as Some"); + + let carried: std::collections::HashSet<&str> = + scope.allow.iter().map(String::as_str).collect(); + assert_eq!( + carried, + allowed + .iter() + .map(String::as_str) + .collect::>() + ); + + assert!(scope.allows_source_id("src-abc")); + assert!(scope.allows_source_id("mem_src:src-abc:item-1")); + assert!(!scope.allows_source_id("src-xyz")); + }) + .await; +} diff --git a/crates/openhuman-core/src/memory/sources/hosted_periodic.rs b/crates/openhuman-core/src/memory/sources/hosted_periodic.rs new file mode 100644 index 00000000000..725b84af2aa --- /dev/null +++ b/crates/openhuman-core/src/memory/sources/hosted_periodic.rs @@ -0,0 +1,245 @@ +//! Scheduled syncs of the local memory sources when the host syncs them. +//! +//! With the embedded engine, the TinyMemory module refreshes folder, GitHub, +//! RSS and web-page sources on a schedule of its own. A driver that keeps what +//! it is sent and runs no source pipeline (hosted memory; see +//! [`super::hosted_sync`]) has no such schedule, so without this loop those +//! sources would change only when the user pressed Sync. It runs each due +//! source through the same host sync the Sync button reaches, recorded the +//! same way, and it keeps the engine loop's rules: +//! +//! - the cadence is the user's `memory_sync_interval_secs`, never shorter than +//! a day, and `0` means manual only; +//! - a source is due when its last run from this loop, or its last successful +//! run in the host's run log, is older than that — so a restart does not +//! sync everything again; +//! - nothing runs while the user is signed out or has turned background work +//! off; +//! - nothing runs unless the driver bound at that tick is one the host syncs, +//! because the engine can be switched while the app runs. +//! +//! Connector sources are not scheduled here; the periodic Composio loop owns +//! them. Nor are conversations and searches, which the engine's loop does not +//! schedule either. + +use std::collections::HashMap; +use std::sync::{Mutex, OnceLock, PoisonError}; +use std::time::{Duration, Instant}; + +use chrono::{DateTime, Utc}; + +use crate::config::DEFAULT_MEMORY_SYNC_INTERVAL_SECS; +use crate::cron::scheduler_gate::PauseReason; +use crate::memory::api::provider::sync::SyncAuditEntry; +use crate::memory::sources::hosted_sync; +use crate::memory::sources::rpc::driver_run; +use crate::memory::sources::run_history; +use crate::memory::sources::types::{MemorySourceEntry, SourceKind}; + +/// How often the loop looks for due sources. The per-source cadence, a day at +/// least, bounds how often each one runs; this bounds how late past due it +/// can start. +const TICK: Duration = Duration::from_secs(1200); + +/// Guards [`start_hosted_periodic_sync`] against a second loop. +static STARTED: OnceLock<()> = OnceLock::new(); + +/// When this loop last started each source, by source id. +fn last_fired() -> &'static Mutex> { + static FIRED: OnceLock>> = OnceLock::new(); + FIRED.get_or_init(|| Mutex::new(HashMap::new())) +} + +/// Start the loop. Idempotent. Each tick does nothing unless the driver bound +/// at that moment is one the host syncs, so an embedded engine, whose module +/// schedules these sources itself, is left to it. +pub fn start_hosted_periodic_sync() { + if STARTED.set(()).is_err() { + tracing::debug!("[memory_sources:hosted_periodic] loop already running"); + return; + } + tracing::info!( + tick_secs = TICK.as_secs(), + "[memory_sources:hosted_periodic] starting the scheduled sync of local sources" + ); + tokio::spawn(async move { + let mut ticker = tokio::time::interval(TICK); + // The first tick fires at once; skip it so startup is not spent + // syncing before the user has even signed in. + ticker.tick().await; + loop { + ticker.tick().await; + match run_one_tick().await { + Ok(0) => {} + Ok(ran) => tracing::debug!(ran, "[memory_sources:hosted_periodic] tick done"), + Err(error) => { + tracing::warn!(%error, "[memory_sources:hosted_periodic] tick failed"); + } + } + } + }); +} + +/// One pass: run every due source, one after another, and answer how many +/// ran. +async fn run_one_tick() -> Result { + if let Some(reason) = pause_reason() { + tracing::debug!( + ?reason, + "[memory_sources:hosted_periodic] background work is paused; skipping" + ); + return Ok(0); + } + let config = crate::config::rpc::load_config_with_timeout().await?; + let binding = crate::memory::binding::for_config(&config)?; + let provider = binding.provider(); + if !hosted_sync::host_synced(provider.as_ref()) { + return Ok(0); + } + let Some(sink) = provider.as_sources() else { + return Ok(0); + }; + let Some(interval_secs) = effective_interval_secs(config.memory_sync_interval_secs) else { + tracing::debug!("[memory_sources:hosted_periodic] manual-only; skipping"); + return Ok(0); + }; + let history = match run_history::read_runs(&config.workspace_dir, run_history::KEEP_ROWS) { + Ok(entries) => Some(last_success_by_source(&entries)), + Err(error) => { + tracing::warn!( + %error, + "[memory_sources:hosted_periodic] run log unreadable; only sources this \ + process has run are considered" + ); + None + } + }; + let sources = crate::memory::sources::registry::list_sources_in(&config)?; + let fired: HashMap = last_fired() + .lock() + .unwrap_or_else(PoisonError::into_inner) + .iter() + .map(|(source_id, at)| (source_id.clone(), at.elapsed())) + .collect(); + let due = due_sources( + &sources, + interval_secs, + &fired, + history.as_ref(), + Utc::now(), + ); + if due.is_empty() { + return Ok(0); + } + + let mut ran = 0; + for source in due { + // Recorded before the run, success or not, so a source that keeps + // failing waits out its interval rather than retrying every tick. + last_fired() + .lock() + .unwrap_or_else(PoisonError::into_inner) + .insert(source.id.clone(), Instant::now()); + tracing::info!( + source_id = %source.id, + kind = source.kind.as_str(), + interval_secs, + "[memory_sources:hosted_periodic] syncing a due source" + ); + let result = driver_run::run_recorded( + &config, + &source.id, + Some(source), + || hosted_sync::run(&config, source, sink), + |error| error.to_string(), + driver_run::bus_stage_publisher(driver_run::PERIODIC, &source.id, source.kind.as_str()), + ) + .await; + if let Err(error) = result { + tracing::warn!( + source_id = %source.id, + %error, + "[memory_sources:hosted_periodic] sync failed; retried when next due" + ); + } + ran += 1; + } + Ok(ran) +} + +/// Why background work is paused, when it is for a reason this loop honours: +/// the user turned it off, or is signed out. Battery and CPU pressure throttle +/// LLM work; a sync that is due a day at a time is not held back by them. +fn pause_reason() -> Option { + let reason = crate::cron::scheduler_gate::current_policy().pause_reason()?; + matches!(reason, PauseReason::UserDisabled | PauseReason::SignedOut).then_some(reason) +} + +/// The cadence in seconds for the user's setting, or `None` for manual only. +/// Never shorter than the default day, as the engine's loop rules. +fn effective_interval_secs(configured: Option) -> Option { + match configured { + Some(0) => None, + Some(secs) => Some(secs.max(DEFAULT_MEMORY_SYNC_INTERVAL_SECS)), + None => Some(DEFAULT_MEMORY_SYNC_INTERVAL_SECS), + } +} + +/// Source kinds this loop schedules. +fn is_scheduled_kind(kind: &SourceKind) -> bool { + hosted_sync::serves(kind) +} + +/// The newest successful run of each scheduled source in the run log. +fn last_success_by_source(entries: &[SyncAuditEntry]) -> HashMap> { + let mut newest: HashMap> = HashMap::new(); + for entry in entries.iter().filter(|entry| { + entry.success + && matches!( + entry.source_kind.as_str(), + "folder" | "github_repo" | "rss_feed" | "web_page" + ) + }) { + newest + .entry(entry.source_id.clone()) + .and_modify(|at| *at = (*at).max(entry.timestamp)) + .or_insert(entry.timestamp); + } + newest +} + +/// The enabled, scheduled sources whose last run is at least `interval_secs` +/// old at `now`. +/// +/// A source this process ran is timed from that run (`fired` holds how long +/// ago each started). Otherwise it is timed from its last success in the run +/// log, and one with none there has never synced and is due. Without a +/// readable log, only sources this process ran can be timed, so the rest wait +/// rather than all running at once. +fn due_sources<'a>( + sources: &'a [MemorySourceEntry], + interval_secs: u64, + fired: &HashMap, + history: Option<&HashMap>>, + now: DateTime, +) -> Vec<&'a MemorySourceEntry> { + let interval = Duration::from_secs(interval_secs); + sources + .iter() + .filter(|source| source.enabled && is_scheduled_kind(&source.kind)) + .filter(|source| { + let since = match (fired.get(&source.id), history) { + (Some(elapsed), _) => Some(*elapsed), + (None, Some(history)) => history + .get(&source.id) + .map(|at| (now - *at).to_std().unwrap_or_default()), + (None, None) => return false, + }; + since.is_none_or(|since| since >= interval) + }) + .collect() +} + +#[cfg(test)] +#[path = "hosted_periodic_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/memory/sources/hosted_periodic_tests.rs b/crates/openhuman-core/src/memory/sources/hosted_periodic_tests.rs new file mode 100644 index 00000000000..a693485f866 --- /dev/null +++ b/crates/openhuman-core/src/memory/sources/hosted_periodic_tests.rs @@ -0,0 +1,136 @@ +//! The hosted-memory schedule for local sources: its cadence, and which +//! sources a tick finds due. + +use std::collections::HashMap; +use std::time::Duration; + +use chrono::{DateTime, TimeZone, Utc}; + +use super::*; +use crate::memory::sources::run_history::HostRun; + +const DAY: u64 = 86_400; + +fn now() -> DateTime { + Utc.timestamp_opt(1_789_000_000, 0) + .single() + .expect("a valid instant") +} + +fn source(id: &str, kind: &str, enabled: bool) -> MemorySourceEntry { + serde_json::from_value(serde_json::json!({ + "id": id, + "kind": kind, + "label": id, + "enabled": enabled, + "path": ".", + "url": "https://example.test/feed.xml", + "toolkit": "gmail", + "connection_id": "conn-1", + })) + .expect("a valid source entry") +} + +fn row(source_id: &str, kind: &str, hours_ago: i64, failed: bool) -> SyncAuditEntry { + HostRun { + source_id: source_id.to_string(), + source_kind: kind.to_string(), + scope: source_id.to_string(), + error: failed.then(|| "offline".to_string()), + ..HostRun::default() + } + .into_entry(now() - chrono::Duration::hours(hours_ago)) +} + +fn ids(due: &[&MemorySourceEntry]) -> Vec { + due.iter().map(|source| source.id.clone()).collect() +} + +#[test] +fn the_cadence_is_a_day_at_least_and_zero_is_manual_only() { + assert_eq!(effective_interval_secs(None), Some(DAY)); + assert_eq!(effective_interval_secs(Some(0)), None); + assert_eq!(effective_interval_secs(Some(3_600)), Some(DAY)); + assert_eq!(effective_interval_secs(Some(2 * DAY)), Some(2 * DAY)); +} + +#[test] +fn only_enabled_local_sources_are_scheduled() { + let sources = vec![ + source("notes", "folder", true), + source("repo", "github_repo", true), + source("feed", "rss_feed", true), + source("page", "web_page", true), + source("off", "folder", false), + source("mail", "composio", true), + source("chats", "conversation", true), + source("search", "twitter_query", true), + ]; + let due = due_sources(&sources, DAY, &HashMap::new(), Some(&HashMap::new()), now()); + assert_eq!(ids(&due), ["notes", "repo", "feed", "page"]); +} + +/// The run log times a source across restarts: a recent success waits, an old +/// one or none at all is due, and a failure does not count as a run. +#[test] +fn the_run_log_decides_what_is_due_after_a_restart() { + let sources = vec![ + source("fresh", "folder", true), + source("stale", "folder", true), + source("failing", "folder", true), + source("never", "folder", true), + ]; + let history = last_success_by_source(&[ + row("fresh", "folder", 2, false), + row("stale", "folder", 30, false), + row("stale", "folder", 26, false), + row("failing", "folder", 1, true), + row("mail", "composio", 1, false), + ]); + assert!(!history.contains_key("failing"), "a failure is not a run"); + assert!( + !history.contains_key("mail"), + "connectors are not timed here" + ); + assert_eq!( + history["stale"], + now() - chrono::Duration::hours(26), + "the newest success wins" + ); + let due = due_sources(&sources, DAY, &HashMap::new(), Some(&history), now()); + assert_eq!(ids(&due), ["stale", "failing", "never"]); +} + +/// This process's own runs time a source before the log does, and without a +/// readable log only those can be timed at all. +#[test] +fn this_process_times_what_it_ran() { + let sources = vec![ + source("ran", "folder", true), + source("unknown", "folder", true), + ]; + let just_now = HashMap::from([("ran".to_string(), Duration::from_secs(60))]); + let long_ago = HashMap::from([("ran".to_string(), now() - chrono::Duration::days(9))]); + assert!( + due_sources(&sources, DAY, &just_now, Some(&long_ago), now()) + .iter() + .all(|source| source.id != "ran"), + "a run in this process is newer than the log says" + ); + let due = due_sources(&sources, DAY, &just_now, None, now()); + assert!(due.is_empty(), "without the log, an untimed source waits"); + + let yesterday = HashMap::from([("ran".to_string(), Duration::from_secs(DAY + 60))]); + assert_eq!( + ids(&due_sources(&sources, DAY, &yesterday, None, now())), + ["ran"] + ); +} + +/// A log stamped in the future, from a clock that moved, reads as just run. +#[test] +fn a_run_stamped_in_the_future_is_not_due() { + let sources = vec![source("skewed", "folder", true)]; + let history = HashMap::from([("skewed".to_string(), now() + chrono::Duration::hours(3))]); + assert!(due_sources(&sources, DAY, &HashMap::new(), Some(&history), now()).is_empty()); +} diff --git a/crates/openhuman-core/src/memory/sources/hosted_sync.rs b/crates/openhuman-core/src/memory/sources/hosted_sync.rs new file mode 100644 index 00000000000..4d9b1427a00 --- /dev/null +++ b/crates/openhuman-core/src/memory/sources/hosted_sync.rs @@ -0,0 +1,438 @@ +//! Local sources the host syncs into a driver's source sink. +//! +//! The embedded engine runs its own pipeline behind `MemorySourceSync`: it +//! reads a folder, a repository, a feed or a page, tracks what changed, and +//! ingests it. Hosted memory runs none — it keeps what it is sent through its +//! source sink — so for a driver that serves the sink but not the pipeline +//! ([`host_synced`]), the host reads the source itself and sends the items. +//! The Sync button, Apply all and the periodic loop all come here for such a +//! driver. +//! +//! # What a run does +//! +//! It lists the source's items with the source's reader, newest first and none +//! older than `sync_depth_days`, and works only on what is new or changed since +//! the sink last accepted it: an item whose modified time matches what was +//! recorded is not read at all, and one read whose text is unchanged is not +//! sent. New and changed items go to `accept_source_items` in batches, and what +//! each accepted batch held is recorded once the sink has taken it. +//! +//! `max_items` caps the new or changed items a run sends, and +//! `max_tokens_per_sync` caps their text, at about four characters a token. +//! Either cap stops the run with more pending, and because what was sent is +//! recorded, the next run carries on past it rather than re-sending the same +//! newest items. +//! +//! The record is the host's, one small file per source, and it only ever saves +//! work: a missing or unreadable one is a full pass, which the sink makes +//! cheap by skipping what it already holds unchanged. +//! +//! # What it does not do +//! +//! An item removed from the source stays in memory: the sink forgets a whole +//! source, never one item by its id. Removing a source from the registry stops +//! its syncs and keeps what it synced, as on the local engine; deleting the +//! source's memory (`memory_tree.delete_source`) forgets all of it and clears +//! this record, so a later sync starts over. + +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, OnceLock, PoisonError}; + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use tinymemory_sources::types::ContentType; + +use crate::config::Config; +use crate::memory::api::error::MemoryError; +use crate::memory::api::provider::sync::SyncRunOutcome; +use crate::memory::api::provider::types::SourceItem as SinkItem; +use crate::memory::api::provider::{MemoryProvider, MemorySourceSink}; +use crate::memory::api::types::MemoryTaint; +use crate::memory::sources::readers::{folder, github, rss, web_page, SourceReader}; +use crate::memory::sources::rpc::driver_run::PartialFailure; +use crate::memory::sources::types::{MemorySourceEntry, SourceContent, SourceItem, SourceKind}; + +/// Items handed to the sink in one call. +const BATCH: usize = 25; + +/// Characters a token is counted as, for `max_tokens_per_sync`. +const CHARS_PER_TOKEN: u64 = 4; + +/// Where the per-source records live, under the workspace's state directory. +const STATE_DIR: &str = "state/hosted_sync"; + +/// Whether the host syncs local sources for `provider`: it keeps what it is +/// sent, and runs no source pipeline of its own. +pub(crate) fn host_synced(provider: &dyn MemoryProvider) -> bool { + provider.as_source_sync().is_none() && provider.as_sources().is_some() +} + +/// Whether the host syncs sources of `kind`. Connector sources go through the +/// connector, and conversations and X queries have no host reader that feeds a +/// sink. +pub(crate) fn serves(kind: &SourceKind) -> bool { + matches!( + kind, + SourceKind::Folder | SourceKind::GithubRepo | SourceKind::RssFeed | SourceKind::WebPage + ) +} + +/// The reader for `kind`, built here rather than taken from `reader_for`: a +/// run may come from the periodic loop as well as a user's request, and the +/// network readers are handed out only for the kinds a user added as sources +/// to be synced on their schedule. +fn reader(kind: &SourceKind) -> Option> { + match kind { + SourceKind::Folder => Some(Box::new(folder::FolderReader)), + SourceKind::GithubRepo => Some(Box::new(github::GithubReader)), + SourceKind::RssFeed => Some(Box::new(rss::RssReader::new())), + SourceKind::WebPage => Some(Box::new(web_page::WebPageReader)), + _ => None, + } +} + +/// A local folder is the user's own material; anything fetched is not. +fn taint_of(kind: &SourceKind) -> MemoryTaint { + if *kind == SourceKind::Folder { + MemoryTaint::Internal + } else { + MemoryTaint::ExternalSync + } +} + +fn mime_of(content_type: &ContentType) -> &'static str { + match content_type { + ContentType::Markdown => "text/markdown", + ContentType::Html => "text/html", + ContentType::Plaintext => "text/plain", + } +} + +/// The items a run considers: none older than `sync_depth_days`, newest first. +fn chosen(entry: &MemorySourceEntry, mut items: Vec, now_ms: i64) -> Vec { + if let Some(days) = entry.sync_depth_days.filter(|days| *days > 0) { + let floor = now_ms - i64::from(days) * 86_400_000; + items.retain(|item| item.updated_at_ms.is_none_or(|at| at >= floor)); + } + items.sort_by_key(|item| std::cmp::Reverse(item.updated_at_ms)); + items +} + +/// One item as the sink last took it. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +struct Seen { + /// The item's modified time then, when its reader gives one. + #[serde(default, skip_serializing_if = "Option::is_none")] + at: Option, + /// A digest of what was sent: its title, text and URL. + digest: String, +} + +/// What a source's earlier runs handed the sink, by item id. +#[derive(Debug, Default, Serialize, Deserialize)] +struct SyncState { + #[serde(default)] + items: HashMap, +} + +/// The file holding `source_id`'s record. The name is a digest, so any source +/// id makes a safe file name. +fn state_path(config: &Config, source_id: &str) -> PathBuf { + let digest = Sha256::digest(source_id.as_bytes()); + let name: String = digest[..8].iter().map(|b| format!("{b:02x}")).collect(); + config + .workspace_dir + .join(STATE_DIR) + .join(format!("{name}.json")) +} + +/// The record at `path`, or an empty one when there is none or it cannot be +/// read: a full pass costs lookups, never wrong data. +fn load_state(path: &Path) -> SyncState { + match std::fs::read(path) { + Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|error| { + tracing::warn!( + path = %path.display(), + "[memory_sources:hosted_sync] sync record unreadable; doing a full pass: {error}" + ); + SyncState::default() + }), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => SyncState::default(), + Err(error) => { + tracing::warn!( + path = %path.display(), + "[memory_sources:hosted_sync] sync record unreadable; doing a full pass: {error}" + ); + SyncState::default() + } + } +} + +/// Saves the record, replacing the old one whole. A failure is logged and not +/// fatal: the next run re-sends what this one could not record, and the sink +/// skips it. +fn save_state(path: &Path, state: &SyncState) { + let write = || -> std::io::Result<()> { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let tmp = path.with_extension("json.tmp"); + std::fs::write(&tmp, serde_json::to_vec(state)?)?; + std::fs::rename(&tmp, path) + }; + if let Err(error) = write() { + tracing::warn!( + path = %path.display(), + "[memory_sources:hosted_sync] could not save the sync record: {error}" + ); + } +} + +/// Forgets what was recorded for `source_id`, so its next sync is a full pass. +/// Called when the source's memory is deleted or the source is removed. +pub(crate) fn forget_state(config: &Config, source_id: &str) { + let path = state_path(config, source_id); + match std::fs::remove_file(&path) { + Ok(()) => tracing::debug!( + path = %path.display(), + "[memory_sources:hosted_sync] sync record cleared" + ), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => tracing::warn!( + path = %path.display(), + "[memory_sources:hosted_sync] could not clear the sync record: {error}" + ), + } +} + +/// The lock one source's runs take, so a manual sync and a scheduled one do +/// not read and send the same items at once. +fn source_lock(source_id: &str) -> Arc> { + static LOCKS: OnceLock>>>> = OnceLock::new(); + LOCKS + .get_or_init(Default::default) + .lock() + .unwrap_or_else(PoisonError::into_inner) + .entry(source_id.to_string()) + .or_default() + .clone() +} + +fn digest_of(title: &str, content: &SourceContent, url: Option<&str>) -> String { + let mut hasher = Sha256::new(); + for part in [title, &content.body, url.unwrap_or_default()] { + hasher.update((part.len() as u64).to_le_bytes()); + hasher.update(part.as_bytes()); + } + hasher.finalize()[..16] + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +/// A run's batch in flight, and what it has done so far. +struct Progress { + path: PathBuf, + state: SyncState, + batch: Vec, + seen: Vec<(String, Seen)>, + outcome: SyncRunOutcome, +} + +impl Progress { + /// Sends the batch and, once the sink has taken it, records what it held. + async fn flush( + &mut self, + entry: &MemorySourceEntry, + sink: &dyn MemorySourceSink, + ) -> Result<(), MemoryError> { + if self.batch.is_empty() { + return Ok(()); + } + let written = send(entry, sink, std::mem::take(&mut self.batch)).await?; + self.outcome.records_ingested += written; + for (id, seen) in self.seen.drain(..) { + self.state.items.insert(id, seen); + } + save_state(&self.path, &self.state); + Ok(()) + } +} + +/// Syncs `entry` into `sink` once. +/// +/// # Errors +/// +/// [`MemoryError::Unsupported`] for a kind the host does not sync; +/// [`MemoryError::Backend`] when the source cannot be listed; the sink's own +/// error when a batch is refused, with what earlier batches wrote. An item +/// that cannot be read is skipped and counted in the outcome's note. +pub(in crate::memory::sources) async fn run( + config: &Config, + entry: &MemorySourceEntry, + sink: &dyn MemorySourceSink, +) -> Result { + let Some(reader) = reader(&entry.kind) else { + return Err(MemoryError::unsupported_raw(format!( + "host sync of {} sources", + entry.kind.as_str() + )) + .into()); + }; + let lock = source_lock(&entry.id); + let _running = lock.lock().await; + let listed = reader + .list_items(entry, &config.workspace_dir) + .await + .map_err(|error| MemoryError::Backend(format!("listing source '{}': {error}", entry.id)))?; + let listed_ids: HashSet = listed.iter().map(|item| item.id.clone()).collect(); + let total = listed.len(); + let items = chosen(entry, listed, chrono::Utc::now().timestamp_millis()); + let path = state_path(config, &entry.id); + let mut state = load_state(&path); + // An item the source no longer lists has nothing left to compare. + state.items.retain(|id, _| listed_ids.contains(id)); + tracing::debug!( + source_id = %entry.id, + kind = entry.kind.as_str(), + listed = total, + considered = items.len(), + recorded = state.items.len(), + "[memory_sources:hosted_sync] run starting" + ); + let budget = entry + .max_tokens_per_sync + .map(|tokens| tokens.saturating_mul(CHARS_PER_TOKEN)); + let cap = entry.max_items.map(|cap| cap as usize); + let mut spent: u64 = 0; + let mut queued = 0usize; + let mut unreadable = 0usize; + let mut unchanged = 0usize; + let mut more_pending = false; + let mut progress = Progress { + path, + state, + batch: Vec::with_capacity(BATCH), + seen: Vec::with_capacity(BATCH), + outcome: SyncRunOutcome::default(), + }; + for item in items { + let held = progress.state.items.get(&item.id); + if item.updated_at_ms.is_some() && held.is_some_and(|held| held.at == item.updated_at_ms) { + unchanged += 1; + continue; + } + if cap.is_some_and(|cap| queued >= cap) { + more_pending = true; + break; + } + let content = match reader + .read_item(entry, &item.id, &config.workspace_dir) + .await + { + Ok(content) => content, + Err(error) => { + unreadable += 1; + tracing::warn!( + source_id = %entry.id, + item_id = %item.id, + "[memory_sources:hosted_sync] item could not be read: {error}" + ); + continue; + } + }; + let title = if content.title.is_empty() { + item.title.clone() + } else { + content.title.clone() + }; + let url = content + .metadata + .get("url") + .and_then(serde_json::Value::as_str) + .map(str::to_string); + let seen = Seen { + at: item.updated_at_ms, + digest: digest_of(&title, &content, url.as_deref()), + }; + let same_text = progress + .state + .items + .get(&item.id) + .is_some_and(|held| held.digest == seen.digest); + if same_text || content.body.trim().is_empty() { + // Nothing to send. Recording it now lets the next run skip it + // without reading it, by its modified time. + unchanged += 1; + progress.state.items.insert(item.id, seen); + continue; + } + let size = content.body.len() as u64; + if budget.is_some_and(|budget| spent + size > budget) { + more_pending = true; + break; + } + spent += size; + queued += 1; + progress.batch.push(SinkItem { + item_id: item.id.clone(), + title, + content: content.body, + mime: Some(mime_of(&content.content_type).to_string()), + url, + updated_at_ms: item.updated_at_ms, + tags: Vec::new(), + }); + progress.seen.push((item.id, seen)); + if progress.batch.len() == BATCH { + if let Err(error) = progress.flush(entry, sink).await { + return Err(failed(progress, error, more_pending)); + } + } + } + if let Err(error) = progress.flush(entry, sink).await { + return Err(failed(progress, error, more_pending)); + } + // What was read and found unchanged is recorded even when nothing was sent. + save_state(&progress.path, &progress.state); + let mut outcome = progress.outcome; + outcome.more_pending = more_pending; + if unreadable > 0 { + outcome.note = Some(format!("{unreadable} item(s) could not be read")); + } + tracing::debug!( + source_id = %entry.id, + written = outcome.records_ingested, + unchanged, + unreadable, + more_pending, + "[memory_sources:hosted_sync] run finished" + ); + Ok(outcome) +} + +/// A refused batch, with what the run had done before it. The batch that was +/// refused is not recorded, so the next run sends it again. +fn failed(progress: Progress, error: MemoryError, more_pending: bool) -> PartialFailure { + save_state(&progress.path, &progress.state); + let mut done = progress.outcome; + done.more_pending = more_pending; + PartialFailure { error, done } +} + +/// One batch into the sink; answers how many items it wrote. +async fn send( + entry: &MemorySourceEntry, + sink: &dyn MemorySourceSink, + batch: Vec, +) -> Result { + let accepted = sink + .accept_source_items(&entry.id, entry.kind.as_str(), batch, taint_of(&entry.kind)) + .await?; + Ok(accepted.written) +} + +#[cfg(test)] +#[path = "hosted_sync_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/memory/sources/hosted_sync_tests.rs b/crates/openhuman-core/src/memory/sources/hosted_sync_tests.rs new file mode 100644 index 00000000000..6061b571283 --- /dev/null +++ b/crates/openhuman-core/src/memory/sources/hosted_sync_tests.rs @@ -0,0 +1,362 @@ +//! The host's sync of local sources into a driver's sink: which items a run +//! reads, what it sends, the budgets it keeps, and how the next run carries on +//! from what the sink accepted. + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; +use std::time::{Duration, SystemTime}; + +use async_trait::async_trait; + +use super::*; +use crate::memory::api::provider::types::IngestOutcome; + +/// One `accept_source_items` call: source id, source kind, items, taint. +type Batch = (String, String, Vec, MemoryTaint); + +/// A sink that records every batch and writes each item it is handed, or +/// refuses the call numbered `refuse_call` (1-based). +#[derive(Default)] +struct RecordingSink { + batches: Mutex>, + calls: AtomicUsize, + refuse_call: Option, +} + +impl RecordingSink { + fn refusing(call: usize) -> Self { + Self { + refuse_call: Some(call), + ..Self::default() + } + } + + fn items(&self) -> Vec { + self.batches + .lock() + .expect("batches") + .iter() + .flat_map(|(_, _, items, _)| items.clone()) + .collect() + } + + fn item_ids(&self) -> Vec { + let mut ids: Vec = self.items().into_iter().map(|item| item.item_id).collect(); + ids.sort(); + ids + } +} + +#[async_trait] +impl MemorySourceSink for RecordingSink { + async fn accept_source_items( + &self, + source_id: &str, + source_kind: &str, + items: Vec, + taint: MemoryTaint, + ) -> Result { + let call = self.calls.fetch_add(1, Ordering::SeqCst) + 1; + if self.refuse_call == Some(call) { + return Err(MemoryError::Unavailable("memory API unavailable".into())); + } + let written = items.len() as u32; + self.batches.lock().expect("batches").push(( + source_id.to_string(), + source_kind.to_string(), + items, + taint, + )); + Ok(IngestOutcome { + written, + ..IngestOutcome::default() + }) + } + + async fn forget_source(&self, _source_id: &str) -> Result { + Ok(0) + } +} + +fn folder_entry(path: &std::path::Path) -> MemorySourceEntry { + serde_json::from_value(serde_json::json!({ + "id": "notes", + "kind": "folder", + "label": "Notes", + "enabled": true, + "path": path.to_string_lossy(), + })) + .expect("a folder source") +} + +fn listed(id: &str, updated_at_ms: Option) -> SourceItem { + SourceItem { + id: id.to_string(), + title: id.to_string(), + updated_at_ms, + } +} + +fn config(dir: &std::path::Path) -> Config { + Config { + workspace_dir: dir.to_path_buf(), + ..Config::default() + } +} + +/// A folder of `names`, each file `size` characters long, with distinct +/// modified times so the newest-first order is fixed: the first name is the +/// oldest. +fn folder_of(dir: &std::path::Path, names: &[&str], size: usize) -> std::path::PathBuf { + let folder = dir.join("notes"); + std::fs::create_dir_all(&folder).expect("folder"); + let base = SystemTime::now() - Duration::from_secs(3_600); + for (i, name) in names.iter().enumerate() { + write_at( + &folder.join(format!("{name}.md")), + &format!("{name}{}", "x".repeat(size.saturating_sub(name.len()))), + base + Duration::from_secs(i as u64 * 60), + ); + } + folder +} + +fn write_at(path: &std::path::Path, text: &str, modified: SystemTime) { + std::fs::write(path, text).expect("write"); + std::fs::File::options() + .write(true) + .open(path) + .expect("open") + .set_modified(modified) + .expect("set the modified time"); +} + +#[test] +fn the_host_syncs_local_kinds_only() { + for kind in [ + SourceKind::Folder, + SourceKind::GithubRepo, + SourceKind::RssFeed, + SourceKind::WebPage, + ] { + assert!(serves(&kind), "{kind:?}"); + } + for kind in [ + SourceKind::Composio, + SourceKind::Conversation, + SourceKind::TwitterQuery, + ] { + assert!(!serves(&kind), "{kind:?}"); + } + assert_eq!(taint_of(&SourceKind::Folder), MemoryTaint::Internal); + assert_eq!(taint_of(&SourceKind::RssFeed), MemoryTaint::ExternalSync); +} + +#[test] +fn a_run_considers_the_newest_items_within_its_depth() { + let day = 86_400_000; + let now = 100 * day; + let mut entry = folder_entry(std::path::Path::new(".")); + let items = || { + vec![ + listed("old", Some(now - 40 * day)), + listed("new", Some(now - day)), + listed("undated", None), + listed("mid", Some(now - 10 * day)), + ] + }; + let ids = |items: Vec| items.into_iter().map(|i| i.id).collect::>(); + assert_eq!( + ids(chosen(&entry, items(), now)), + ["new", "mid", "old", "undated"] + ); + entry.sync_depth_days = Some(30); + assert_eq!( + ids(chosen(&entry, items(), now)), + ["new", "mid", "undated"], + "an item with no date is kept" + ); +} + +#[tokio::test] +async fn a_folder_is_read_and_sent_to_the_sink() { + let dir = tempfile::tempdir().expect("tempdir"); + let folder = dir.path().join("notes"); + std::fs::create_dir_all(&folder).expect("folder"); + std::fs::write(folder.join("a.md"), "# Tea\n\nOolong is best.").expect("a"); + std::fs::write(folder.join("b.md"), " ").expect("blank"); + std::fs::write(folder.join("skip.txt"), "not markdown").expect("txt"); + let sink = RecordingSink::default(); + let outcome = run(&config(dir.path()), &folder_entry(&folder), &sink) + .await + .expect("run"); + assert_eq!(outcome.records_ingested, 1); + assert!(!outcome.more_pending); + let batches = sink.batches.lock().expect("batches"); + assert_eq!(batches.len(), 1); + let (source_id, kind, items, taint) = &batches[0]; + assert_eq!((source_id.as_str(), kind.as_str()), ("notes", "folder")); + assert_eq!(*taint, MemoryTaint::Internal); + assert_eq!(items.len(), 1, "a blank file is not sent"); + assert!(items[0].content.contains("Oolong is best.")); + assert_eq!(items[0].mime.as_deref(), Some("text/markdown")); +} + +/// What the sink accepted is not sent again; a changed file is. +#[tokio::test] +async fn only_new_or_changed_items_are_sent_again() { + let dir = tempfile::tempdir().expect("tempdir"); + let folder = folder_of(dir.path(), &["a", "b"], 40); + let entry = folder_entry(&folder); + let config = config(dir.path()); + let sink = RecordingSink::default(); + run(&config, &entry, &sink).await.expect("first"); + assert_eq!(sink.item_ids(), ["a.md", "b.md"]); + + let again = RecordingSink::default(); + let outcome = run(&config, &entry, &again).await.expect("unchanged"); + assert!( + again.items().is_empty(), + "an unchanged folder sends nothing" + ); + assert_eq!(outcome.records_ingested, 0); + + write_at(&folder.join("b.md"), "b, rewritten", SystemTime::now()); + let changed = RecordingSink::default(); + run(&config, &entry, &changed).await.expect("changed"); + assert_eq!(changed.item_ids(), ["b.md"]); +} + +/// A run stopped by its budget is picked up where it stopped, not restarted +/// from the newest items, so a source larger than its budget still syncs. +#[tokio::test] +async fn a_budget_limited_sync_carries_on_across_runs() { + let dir = tempfile::tempdir().expect("tempdir"); + let folder = folder_of(dir.path(), &["a", "b", "c"], 400); + let mut entry = folder_entry(&folder); + // 600 characters: one 400-character file a run. + entry.max_tokens_per_sync = Some(150); + let config = config(dir.path()); + let mut sent = Vec::new(); + for _ in 0..3 { + let sink = RecordingSink::default(); + let outcome = run(&config, &entry, &sink).await.expect("run"); + assert_eq!(sink.items().len(), 1); + sent.extend(sink.item_ids()); + if sent.len() < 3 { + assert!(outcome.more_pending); + } + } + assert_eq!(sent, ["c.md", "b.md", "a.md"], "newest first, each once"); + let last = RecordingSink::default(); + let outcome = run(&config, &entry, &last).await.expect("done"); + assert!(last.items().is_empty()); + assert!(!outcome.more_pending); +} + +/// `max_items` caps what one run sends, and the next run continues. +#[tokio::test] +async fn max_items_caps_each_run_and_the_next_one_continues() { + let dir = tempfile::tempdir().expect("tempdir"); + let folder = folder_of(dir.path(), &["a", "b", "c"], 20); + let mut entry = folder_entry(&folder); + entry.max_items = Some(2); + let config = config(dir.path()); + let first = RecordingSink::default(); + let outcome = run(&config, &entry, &first).await.expect("first"); + assert_eq!(first.item_ids(), ["b.md", "c.md"]); + assert!(outcome.more_pending); + let second = RecordingSink::default(); + run(&config, &entry, &second).await.expect("second"); + assert_eq!(second.item_ids(), ["a.md"]); +} + +/// A refused batch fails the run, keeps what earlier batches wrote, and is +/// sent again next time; the earlier batches are not. +#[tokio::test] +async fn a_refused_batch_keeps_earlier_progress_and_is_retried() { + let dir = tempfile::tempdir().expect("tempdir"); + let names: Vec = (0..30).map(|i| format!("n{i:02}")).collect(); + let names: Vec<&str> = names.iter().map(String::as_str).collect(); + let folder = folder_of(dir.path(), &names, 20); + let entry = folder_entry(&folder); + let config = config(dir.path()); + + let refusing = RecordingSink::refusing(2); + let failure = run(&config, &entry, &refusing) + .await + .expect_err("the second batch is refused"); + assert!( + matches!(failure.error, MemoryError::Unavailable(_)), + "{failure:?}" + ); + assert_eq!(failure.done.records_ingested, BATCH as u32); + assert_eq!(refusing.items().len(), BATCH); + + let retry = RecordingSink::default(); + let outcome = run(&config, &entry, &retry).await.expect("retry"); + assert_eq!(retry.items().len(), 30 - BATCH, "only the refused batch"); + assert_eq!(outcome.records_ingested, (30 - BATCH) as u32); +} + +/// Deleting a source's memory clears the record, so the next sync sends +/// everything again rather than trusting what was forgotten. +#[tokio::test] +async fn a_cleared_record_means_a_full_pass() { + let dir = tempfile::tempdir().expect("tempdir"); + let folder = folder_of(dir.path(), &["a", "b"], 20); + let entry = folder_entry(&folder); + let config = config(dir.path()); + run(&config, &entry, &RecordingSink::default()) + .await + .expect("first"); + forget_state(&config, &entry.id); + let again = RecordingSink::default(); + run(&config, &entry, &again).await.expect("after clearing"); + assert_eq!(again.item_ids(), ["a.md", "b.md"]); + // Clearing a record that is not there is a no-op. + forget_state(&config, "never-synced"); +} + +/// A record that cannot be read is a full pass, never a failure. +#[tokio::test] +async fn an_unreadable_record_is_a_full_pass() { + let dir = tempfile::tempdir().expect("tempdir"); + let folder = folder_of(dir.path(), &["a"], 20); + let entry = folder_entry(&folder); + let config = config(dir.path()); + let path = state_path(&config, &entry.id); + std::fs::create_dir_all(path.parent().expect("parent")).expect("dir"); + std::fs::write(&path, b"not json").expect("garbage"); + let sink = RecordingSink::default(); + run(&config, &entry, &sink).await.expect("run"); + assert_eq!(sink.item_ids(), ["a.md"]); +} + +#[tokio::test] +async fn a_missing_folder_or_unserved_kind_fails_the_run() { + let dir = tempfile::tempdir().expect("tempdir"); + let sink = RecordingSink::default(); + let missing = run( + &config(dir.path()), + &folder_entry(&dir.path().join("absent")), + &sink, + ) + .await + .expect_err("a missing folder"); + assert!( + matches!(missing.error, MemoryError::Backend(_)), + "{missing:?}" + ); + assert_eq!(missing.done, SyncRunOutcome::default()); + let mut chats = folder_entry(dir.path()); + chats.kind = SourceKind::Conversation; + let refused = run(&config(dir.path()), &chats, &sink) + .await + .expect_err("an unserved kind"); + assert!( + matches!(refused.error, MemoryError::Unsupported { .. }), + "{refused:?}" + ); + assert!(sink.items().is_empty()); +} diff --git a/crates/openhuman-core/src/memory/sources/mod.rs b/crates/openhuman-core/src/memory/sources/mod.rs index 826d779dfd0..9b2c49b4910 100644 --- a/crates/openhuman-core/src/memory/sources/mod.rs +++ b/crates/openhuman-core/src/memory/sources/mod.rs @@ -104,6 +104,13 @@ pub mod reconcile; // the driver's log by the history RPCs (openhuman#6257). pub(crate) mod run_history; +// Local sources the host reads and sends through a driver's source sink, for a +// driver that runs no source pipeline of its own (hosted memory), and the loop +// that schedules them. +pub(crate) mod hosted_periodic; +pub(crate) mod hosted_sync; +pub use hosted_periodic::start_hosted_periodic_sync; + // The controller aggregators this domain's RPC surface defines. Aliased // exactly as the pre-extraction module exported them. pub use schemas::{ diff --git a/crates/openhuman-core/src/memory/sources/rpc.rs b/crates/openhuman-core/src/memory/sources/rpc.rs index 648842e40c8..86a177abe03 100644 --- a/crates/openhuman-core/src/memory/sources/rpc.rs +++ b/crates/openhuman-core/src/memory/sources/rpc.rs @@ -60,7 +60,7 @@ mod apply_all; mod coding_sessions; mod cost_reporting; -mod driver_run; +pub(in crate::memory::sources) mod driver_run; mod registry_crud; mod source_sync; mod status_toolkits; diff --git a/crates/openhuman-core/src/memory/sources/rpc/apply_all.rs b/crates/openhuman-core/src/memory/sources/rpc/apply_all.rs index 899c5bbe752..8ef66bd4100 100644 --- a/crates/openhuman-core/src/memory/sources/rpc/apply_all.rs +++ b/crates/openhuman-core/src/memory/sources/rpc/apply_all.rs @@ -108,6 +108,12 @@ pub async fn apply_all_in_rpc() -> Result, String> { // the family reports the refusal as its own per-source error, which is // exactly what this sweep aggregates. let source_sync = binding.provider().as_source_sync(); + // A driver that keeps what it is sent and runs no source pipeline (hosted + // memory) is synced by the host through its sink instead. + let host_sink = binding + .provider() + .as_sources() + .filter(|_| crate::memory::sources::hosted_sync::host_synced(binding.provider().as_ref())); let config_ref = &config; let driver_id = binding.driver_id(); @@ -134,18 +140,35 @@ pub async fn apply_all_in_rpc() -> Result, String> { .await .map(|_| ()), SyncDispatch::Driver => { + let publish = super::driver_run::bus_stage_publisher( + super::driver_run::MANUAL, + &source.id, + source.kind.as_str(), + ); + // The same start, finish and history row as the Sync button + // (openhuman#6257), whichever side runs the sync. + if let Some(sink) = host_sink { + return super::driver_run::run_recorded( + config_ref, + &source.id, + Some(&source), + || crate::memory::sources::hosted_sync::run(config_ref, &source, sink), + |error| error.to_string(), + publish, + ) + .await + .map(|_| ()); + } let sync = source_sync.ok_or_else(|| { format!("the bound memory driver '{driver_id}' does not serve source sync") })?; - // The same start, finish and history row as the Sync button - // (openhuman#6257). super::driver_run::run_recorded( config_ref, &source.id, Some(&source), || sync.run_source_sync(&source.id), |error| error.to_string(), - super::driver_run::bus_stage_publisher(&source.id, source.kind.as_str()), + publish, ) .await .map(|_| ()) diff --git a/crates/openhuman-core/src/memory/sources/rpc/driver_run.rs b/crates/openhuman-core/src/memory/sources/rpc/driver_run.rs index df62a675296..1f5546e894c 100644 --- a/crates/openhuman-core/src/memory/sources/rpc/driver_run.rs +++ b/crates/openhuman-core/src/memory/sources/rpc/driver_run.rs @@ -21,7 +21,11 @@ use crate::memory::sources::types::MemorySourceEntry; /// The trigger a user-started driver run reports under — the word the engine's /// `sync_source` used for the Sync button. -const TRIGGER: &str = "manual"; +pub(in crate::memory::sources) const MANUAL: &str = "manual"; + +/// The trigger a scheduled driver run reports under — the word the periodic +/// Composio loop uses for its runs. +pub(in crate::memory::sources) const PERIODIC: &str = "periodic"; /// The scope a history row names for `entry`: the rule the engine's periodic /// writer applies (URL, then toolkit, then the id), so a source's manual and @@ -34,15 +38,16 @@ pub(super) fn history_scope(entry: &MemorySourceEntry) -> String { .unwrap_or_else(|| entry.id.clone()) } -/// The stage event for one driver-backed source. +/// The stage event for one driver-backed source, under `trigger`. pub(super) fn stage_event( + trigger: &str, source_id: &str, kind: &str, stage: &str, detail: Option, ) -> DomainEvent { DomainEvent::MemorySyncStageChanged { - trigger: TRIGGER.to_string(), + trigger: trigger.to_string(), stage: stage.to_string(), provider: Some(kind.to_string()), // The row id here too, as the engine's `sync_source` sent it: the app @@ -54,12 +59,64 @@ pub(super) fn stage_event( } } -/// A stage publisher for one source, on the process bus. -pub(super) fn bus_stage_publisher(source_id: &str, kind: &str) -> impl Fn(&str, Option) { +/// A stage publisher for one source, on the process bus, under `trigger`. +pub(in crate::memory::sources) fn bus_stage_publisher( + trigger: &'static str, + source_id: &str, + kind: &str, +) -> impl Fn(&str, Option) { let source_id = source_id.to_string(); let kind = kind.to_string(); move |stage, detail| { - crate::core::bus::BUS.publish(stage_event(&source_id, &kind, stage, detail)); + crate::core::bus::BUS.publish(stage_event(trigger, &source_id, &kind, stage, detail)); + } +} + +/// A failed run as `run_recorded` reports it: the error, and what the run had +/// done before it failed. +pub(in crate::memory::sources) trait RunFailure { + /// Why the run failed. + fn error(&self) -> &MemoryError; + + /// What the run had done when it failed, when it did anything. + fn done(&self) -> Option<&SyncRunOutcome> { + None + } +} + +/// A driver's own run reports only its error. +impl RunFailure for MemoryError { + fn error(&self) -> &MemoryError { + self + } +} + +/// A run that failed after some of its work: a host-side sync that wrote some +/// batches before one was refused. The run still failed, and its row says how +/// much it wrote first. +#[derive(Debug)] +pub(in crate::memory::sources) struct PartialFailure { + pub(in crate::memory::sources) error: MemoryError, + pub(in crate::memory::sources) done: SyncRunOutcome, +} + +impl RunFailure for PartialFailure { + fn error(&self) -> &MemoryError { + &self.error + } + + fn done(&self) -> Option<&SyncRunOutcome> { + Some(&self.done) + } +} + +/// A failure before any work was done. +impl From for PartialFailure { + fn from(error: MemoryError) -> Self { + Self { + error, + done: SyncRunOutcome::default(), + } } } @@ -73,7 +130,11 @@ pub(super) fn bus_stage_publisher(source_id: &str, kind: &str) -> impl Fn(&str, /// The row is written before the terminal stage is published, on purpose: the /// history panel refetches when that stage arrives, and a row written after it /// would miss that read. -pub(super) async fn run_recorded( +/// +/// A failed row counts what the run wrote before it failed, so a run that +/// stored two batches and then was refused does not read as having stored +/// nothing. It is still a failure. +pub(in crate::memory::sources) async fn run_recorded( config: &Config, source_id: &str, entry: Option<&MemorySourceEntry>, @@ -83,7 +144,8 @@ pub(super) async fn run_recorded( ) -> Result where Run: FnOnce() -> Fut, - Fut: Future>, + Fut: Future>, + Failure: RunFailure, Describe: FnOnce(&MemoryError) -> String, Publish: Fn(&str, Option), { @@ -133,12 +195,19 @@ where ); Ok(outcome) } - Err(error) => { - let message = describe(&error); - record(None, Some(message.clone())); + Err(failure) => { + let mut message = describe(failure.error()); + let done = failure.done(); + if done.is_some_and(|done| done.more_pending) { + // Nothing in the row holds "more pending", so the message says + // it: the run had already stopped at its budget when it failed. + message.push_str(" (the run had stopped at its budget with more items pending)"); + } + record(done, Some(message.clone())); tracing::warn!( source_id = %source_id, error = %message, + written_before_failure = done.map_or(0, |done| done.records_ingested), "[memory_sources:driver_run] run failed" ); publish("failed", Some(message.clone())); diff --git a/crates/openhuman-core/src/memory/sources/rpc/driver_run_tests.rs b/crates/openhuman-core/src/memory/sources/rpc/driver_run_tests.rs index a2b806f2faa..e6265d026a4 100644 --- a/crates/openhuman-core/src/memory/sources/rpc/driver_run_tests.rs +++ b/crates/openhuman-core/src/memory/sources/rpc/driver_run_tests.rs @@ -41,7 +41,7 @@ async fn a_completed_run_publishes_its_start_and_finish_and_records_a_row() { "src_notes", Some(&entry), || async { - Ok(SyncRunOutcome { + Ok::<_, MemoryError>(SyncRunOutcome { records_ingested: 3, ..SyncRunOutcome::default() }) @@ -84,7 +84,7 @@ async fn a_completed_run_that_stopped_short_says_so_in_its_detail() { "src_capped", Some(&folder("src_capped")), || async { - Ok(SyncRunOutcome { + Ok::<_, MemoryError>(SyncRunOutcome { records_ingested: 50, more_pending: true, note: Some("per-source item limit reached".to_string()), @@ -147,6 +147,45 @@ async fn a_failed_run_publishes_the_described_failure_and_records_it() { assert_eq!(rows[0].items_fetched, 0); } +/// A run that wrote some batches before one was refused still fails, and its +/// row counts what it wrote first rather than reading as having stored +/// nothing; a budget stop before the failure is said in the message. +#[tokio::test] +async fn a_failure_after_partial_work_records_what_was_written() { + let dir = tempfile::tempdir().expect("tempdir"); + let config = config_in(dir.path()); + let entry = folder("src_partial"); + let stages = Stages::default(); + + let message = run_recorded( + &config, + "src_partial", + Some(&entry), + || async { + Err(PartialFailure { + error: MemoryError::Unavailable("memory API unavailable".to_string()), + done: SyncRunOutcome { + records_ingested: 25, + more_pending: true, + ..SyncRunOutcome::default() + }, + }) + }, + |error| format!("described: {error}"), + publisher(&stages), + ) + .await + .expect_err("the run failed"); + + assert!(message.starts_with("described: "), "{message}"); + assert!(message.contains("more items pending"), "{message}"); + let rows = read_runs(dir.path(), KEEP_ROWS).expect("read the run log"); + assert_eq!(rows.len(), 1); + assert!(!rows[0].success, "a partial run is still a failure"); + assert_eq!(rows[0].items_fetched, 25); + assert_eq!(rows[0].error.as_deref(), Some(message.as_str())); +} + /// The history panel refetches when the terminal stage arrives, so the row /// has to be on disk by then. #[tokio::test] @@ -159,7 +198,7 @@ async fn the_row_is_on_disk_before_the_terminal_stage_goes_out() { &config, "src_unknown", None, - || async { Ok(SyncRunOutcome::default()) }, + || async { Ok::<_, MemoryError>(SyncRunOutcome::default()) }, |_| unreachable!("a completed run has no failure to describe"), |stage: &str, _detail: Option| { if stage == "completed" { @@ -196,6 +235,7 @@ fn the_history_scope_prefers_the_url_then_the_toolkit_then_the_id() { #[test] fn the_stage_event_names_the_source_for_the_row_indicator() { match stage_event( + MANUAL, "src_ev", "folder", "completed", diff --git a/crates/openhuman-core/src/memory/sources/rpc/registry_crud.rs b/crates/openhuman-core/src/memory/sources/rpc/registry_crud.rs index b831c8702a6..dddb657eb79 100644 --- a/crates/openhuman-core/src/memory/sources/rpc/registry_crud.rs +++ b/crates/openhuman-core/src/memory/sources/rpc/registry_crud.rs @@ -231,6 +231,12 @@ pub struct RemoveResponse { pub async fn remove_rpc(req: RemoveRequest) -> Result, String> { tracing::info!(id = %req.id, "[memory_sources] remove_rpc: entry"); let removed = registry::remove_source(&req.id).await?; + if removed { + // A removed source is never synced again, so the host's record of + // what it sent goes with it. Its memory stays, as on the local engine. + let config = config_rpc::load_config_with_timeout().await?; + crate::memory::sources::hosted_sync::forget_state(&config, &req.id); + } Ok(Outcome::new(RemoveResponse { removed }, vec![])) } diff --git a/crates/openhuman-core/src/memory/sources/rpc/source_sync.rs b/crates/openhuman-core/src/memory/sources/rpc/source_sync.rs index 2435953ed25..a6fd5837dca 100644 --- a/crates/openhuman-core/src/memory/sources/rpc/source_sync.rs +++ b/crates/openhuman-core/src/memory/sources/rpc/source_sync.rs @@ -155,30 +155,57 @@ pub async fn sync_rpc(req: SyncRequest) -> Result, String> )); } } - // Resolved after the composio branch on purpose: the connector-backed - // dispatch above needs `as_sources`, not `as_source_sync`, and a driver - // serving the former without the latter must not fail a composio sync on - // a capability it never uses (review finding on #5932). - let sync = binding.provider().as_source_sync().ok_or_else(|| { - format!( - "the bound memory driver '{}' does not serve source sync", - binding.driver_id() - ) - })?; - // `run_source_sync` reports neither the run's start nor its finish and - // writes no history row; `run_recorded` owns all three (openhuman#6257). let kind = host_entry .as_ref() .map_or("unknown", |entry| entry.kind.as_str()); - super::driver_run::run_recorded( - &config, - &req.source_id, - host_entry.as_ref(), - || sync.run_source_sync(&req.source_id), - |error| describe_source_sync_failure(&req.source_id, host_entry.is_some(), error), - super::driver_run::bus_stage_publisher(&req.source_id, kind), - ) - .await?; + let publish = + super::driver_run::bus_stage_publisher(super::driver_run::MANUAL, &req.source_id, kind); + let provider = binding.provider(); + if crate::memory::sources::hosted_sync::host_synced(provider.as_ref()) { + // A driver that keeps what it is sent and runs no source pipeline of + // its own (hosted memory): the host reads the source and sends the + // items through the driver's sink, recorded like any other run. + let entry = host_entry + .as_ref() + .ok_or_else(|| format!("unknown memory source '{}'", req.source_id))?; + let sink = provider.as_sources().ok_or_else(|| { + format!( + "the bound memory driver '{}' does not accept source items", + binding.driver_id() + ) + })?; + super::driver_run::run_recorded( + &config, + &req.source_id, + Some(entry), + || crate::memory::sources::hosted_sync::run(&config, entry, sink), + |error| error.to_string(), + publish, + ) + .await?; + } else { + // Resolved after the composio branch on purpose: the connector-backed + // dispatch above needs `as_sources`, not `as_source_sync`, and a driver + // serving the former without the latter must not fail a composio sync + // on a capability it never uses (review finding on #5932). + let sync = provider.as_source_sync().ok_or_else(|| { + format!( + "the bound memory driver '{}' does not serve source sync", + binding.driver_id() + ) + })?; + // `run_source_sync` reports neither the run's start nor its finish and + // writes no history row; `run_recorded` owns all three (openhuman#6257). + super::driver_run::run_recorded( + &config, + &req.source_id, + host_entry.as_ref(), + || sync.run_source_sync(&req.source_id), + |error| describe_source_sync_failure(&req.source_id, host_entry.is_some(), error), + publish, + ) + .await?; + } Ok(Outcome::new( SyncResponse { diff --git a/crates/openhuman-core/src/memory/sync_events_bridge_tests.rs b/crates/openhuman-core/src/memory/sync_events_bridge_tests.rs index bf8fe877f27..9277a3ddf55 100644 --- a/crates/openhuman-core/src/memory/sync_events_bridge_tests.rs +++ b/crates/openhuman-core/src/memory/sync_events_bridge_tests.rs @@ -131,43 +131,31 @@ async fn memory_ingestion_started_emits_ingesting_stage() { // ── extract_mem_src_id tests ────────────────────────────────────────── #[test] -fn extract_mem_src_id_parses_simple_source() { - // "mem_src::" → source_id - assert_eq!( - extract_mem_src_id("mem_src:src-abc-123:item-1"), - Some("src-abc-123") - ); -} - -#[test] -fn extract_mem_src_id_parses_item_id_with_colons_in_it() { - // item_id may contain colons (e.g. RSS GUIDs that are URLs). - // source_id is the first segment after "mem_src:"; item_id is everything after. - assert_eq!( - extract_mem_src_id("mem_src:src-rss-42:https://example.com/feed/item-7"), - Some("src-rss-42") - ); - // Web-page item ids may also contain colons. - assert_eq!( - extract_mem_src_id("mem_src:src-web-99:https://blog.example.com/2024/post"), - Some("src-web-99") - ); -} - -#[test] -fn extract_mem_src_id_returns_none_for_non_mem_src() { - // Channel-provider syncs like "slack:workspace-1" have no mem_src prefix. - assert_eq!(extract_mem_src_id("slack:workspace-1"), None); - assert_eq!(extract_mem_src_id("gmail:alice-thread-1"), None); - assert_eq!(extract_mem_src_id("no-prefix"), None); -} - -#[test] -fn extract_mem_src_id_returns_none_for_missing_item_id() { - // "mem_src:" with no item_id separator is invalid. - assert_eq!(extract_mem_src_id("mem_src:source-only-no-item"), None); - // "mem_src::" with empty item_id is also invalid. - assert_eq!(extract_mem_src_id("mem_src:src-abc:"), None); +fn extract_mem_src_id_returns_the_source_segment_of_mem_src_ids() { + // "mem_src::" -> source_id. The item id may itself + // contain colons (RSS GUIDs / URLs); only the first segment is the source. + let cases = [ + // (input, expected) + ("mem_src:src-abc-123:item-1", Some("src-abc-123")), + ( + "mem_src:src-rss-42:https://example.com/feed/item-7", + Some("src-rss-42"), + ), + ( + "mem_src:src-web-99:https://blog.example.com/2024/post", + Some("src-web-99"), + ), + // Channel-provider syncs have no mem_src prefix. + ("slack:workspace-1", None), + ("gmail:alice-thread-1", None), + ("no-prefix", None), + // Missing / empty item id is invalid. + ("mem_src:source-only-no-item", None), + ("mem_src:src-abc:", None), + ]; + for (input, expected) in cases { + assert_eq!(extract_mem_src_id(input), expected, "{input}"); + } } // ── bridge populates source_id for Stored/Queued (DocumentCanonicalized) ── diff --git a/crates/openhuman-core/src/modules/memory/capabilities.rs b/crates/openhuman-core/src/modules/memory/capabilities.rs index 80ccd449816..a2adceefbdd 100644 --- a/crates/openhuman-core/src/modules/memory/capabilities.rs +++ b/crates/openhuman-core/src/modules/memory/capabilities.rs @@ -10,7 +10,7 @@ use tinymemory_api::capabilities::{Capabilities, Capability}; /// Checked against the registry pin by `the_capability_list_matches_the_pinned_release`, /// so bumping the pin without re-reading the list is a red test rather than a /// silent over-claim. -pub(crate) const ARTIFACT_CAPABILITIES_PIN: &str = "1.17.0"; +pub(crate) const ARTIFACT_CAPABILITIES_PIN: &str = "1.20.0"; /// The capability families the **pinned artifact** actually serves. /// @@ -40,6 +40,12 @@ pub(crate) const ARTIFACT_CAPABILITIES_PIN: &str = "1.17.0"; /// is empty (the release adds the remote-engine factory, the hosted CortexDB /// wire and `migrate`, none of which the module serves), so the advertised /// families stay the same. +/// Re-read at `v1.20.0`: `git diff v1.17.0..v1.20.0 -- +/// crates/tinymemory-api/src/capabilities.rs crates/tinymemory-bus/src/capabilities.rs` +/// is empty. v1.18.0 and v1.19.0 moved host-side memory code into library +/// crates, and v1.20.0 adds the hosted families on the TinyHumans wire and +/// the optional `TreeSummary::preview` (contract 4.2); none of that is a family +/// the module serves, so the advertised families stay the same. /// /// Read at tag `v1.3.0`. Unchanged from v1.2.0 — the release added members /// within existing families (`retry_failed`, the diagnostics trio, diff --git a/crates/openhuman-core/src/modules/registry/records_memory_juice.rs b/crates/openhuman-core/src/modules/registry/records_memory_juice.rs index 29a019bc064..0cf9e57ad7d 100644 --- a/crates/openhuman-core/src/modules/registry/records_memory_juice.rs +++ b/crates/openhuman-core/src/modules/registry/records_memory_juice.rs @@ -9,63 +9,63 @@ pub(crate) const TINYMEMORY: ModuleRecord = ModuleRecord { description: "Local memory engine: store, ranked recall, and portable export", bus_name: "ai.tinyhumans.tinymemory.Memory", object_path: "/ai/tinyhumans/tinymemory/Memory", - version: "1.17.0", - release_url: "https://github.com/tinyhumansai/tinymemory/releases/tag/v1.17.0", + version: "1.20.0", + release_url: "https://github.com/tinyhumansai/tinymemory/releases/tag/v1.20.0", assets: &[ PlatformAsset { host_key: "ubuntu-24.04-x86_64", - archive: "tinymemory-module-1.17.0-ubuntu-24.04-x86_64.tar.gz", - sha256: "c3da7f6a0bfae1224d8f3cda9382b6236f8118d60c96ce8b26fea8f16234ed08", + archive: "tinymemory-module-1.20.0-ubuntu-24.04-x86_64.tar.gz", + sha256: "f2e2355098e358388fc59525ae796a2ee221aea26805fa8fc9870962067cc945", }, PlatformAsset { host_key: "ubuntu-24.04-arm64", - archive: "tinymemory-module-1.17.0-ubuntu-24.04-arm64.tar.gz", - sha256: "57cc138a6dcf77eeaed2f9f8d27182713966e855c5db66b80b5857a8ca8ff236", + archive: "tinymemory-module-1.20.0-ubuntu-24.04-arm64.tar.gz", + sha256: "e02423896248f374c0c1fab7a0868449e046238a6e9b0001e9ff7e46799aea77", }, PlatformAsset { host_key: "ubuntu-22.04-x86_64", - archive: "tinymemory-module-1.17.0-ubuntu-22.04-x86_64.tar.gz", - sha256: "0b0305bddbee09b3fe9965395fe9d006526f0c0c2ffd777d6e78747b2cfcff35", + archive: "tinymemory-module-1.20.0-ubuntu-22.04-x86_64.tar.gz", + sha256: "d3c2485a3fdd657b40ba65ab266950bd3f3f060695a9bba3e20b2d83e343fb61", }, PlatformAsset { host_key: "ubuntu-22.04-arm64", - archive: "tinymemory-module-1.17.0-ubuntu-22.04-arm64.tar.gz", - sha256: "b6966f6c3d7c7d4b34f6b0c5d28077dee8809120326daa163b838b1d876c36d0", + archive: "tinymemory-module-1.20.0-ubuntu-22.04-arm64.tar.gz", + sha256: "0a8a54ce6569782d1852c9e8ffefd0e6bb3c35c30ecb9357642cf94bcee5d81f", }, PlatformAsset { host_key: "macos-26-arm64", - archive: "tinymemory-module-1.17.0-macos-26-arm64.tar.gz", - sha256: "c1e39dcef00f37ce0a2ff708790b5de04814ce113cfa7f16bf190fcfaa49645e", + archive: "tinymemory-module-1.20.0-macos-26-arm64.tar.gz", + sha256: "f62caa85b7e091714e8abcc4f5bcbe47265518f058a7d66326049c64fd209d5b", }, PlatformAsset { host_key: "macos-26-x86_64", - archive: "tinymemory-module-1.17.0-macos-26-x86_64.tar.gz", - sha256: "ef59b7c3549c6c718ba26871b9ab54322f248d9b0c8219b265b56d00f6e280a9", + archive: "tinymemory-module-1.20.0-macos-26-x86_64.tar.gz", + sha256: "b13d93054145a3a0159ff4df61bd837cfb6cd2aec1e7631fff0d937b050acf8c", }, PlatformAsset { host_key: "macos-15-arm64", - archive: "tinymemory-module-1.17.0-macos-15-arm64.tar.gz", - sha256: "09a0a27e09e8986d3dbe1f5c32594796b12f59b7d7822afdd746c3514f704788", + archive: "tinymemory-module-1.20.0-macos-15-arm64.tar.gz", + sha256: "94b7bcaa893fb52a690ce870139e8387636a23c2ab180afbae2a39049687cf69", }, PlatformAsset { host_key: "macos-15-x86_64", - archive: "tinymemory-module-1.17.0-macos-15-x86_64.tar.gz", - sha256: "31df68800cec34555a0432b1f057faf2e5cc74af95b43557349d1655d2825ce0", + archive: "tinymemory-module-1.20.0-macos-15-x86_64.tar.gz", + sha256: "cf7073d557d7b9b85c2f3face27584101904675d0b5728cabf54ab03c46a3de8", }, PlatformAsset { host_key: "windows-2025-x86_64", - archive: "tinymemory-module-1.17.0-windows-2025-x86_64.zip", - sha256: "120619d1f1efc4627d7f8418b69cde94c89274f20b4d4c3ed6bb5d9ed23637cf", + archive: "tinymemory-module-1.20.0-windows-2025-x86_64.zip", + sha256: "22a38f8e43c734f355636a3e36c710f72fa9f1611232ee6197f2a3c800bf7f7f", }, PlatformAsset { host_key: "windows-2022-x86_64", - archive: "tinymemory-module-1.17.0-windows-2022-x86_64.zip", - sha256: "825938f178675ad488a7add4b4f4c78c0cf5107d589f05c1bfbbd459a9e94e33", + archive: "tinymemory-module-1.20.0-windows-2022-x86_64.zip", + sha256: "36579172066bcee245bfd5f94fcf6523f892d1daf6f219dea8a50879094c8ccc", }, PlatformAsset { host_key: "windows-11-arm64", - archive: "tinymemory-module-1.17.0-windows-11-arm64.zip", - sha256: "56cf207610e58cf70afed2752a2a76a16e2542d2255c0b1719d54f2a7373bf1d", + archive: "tinymemory-module-1.20.0-windows-11-arm64.zip", + sha256: "5d016281aa6e719a5ae08e6482bc53e17527afba9e2d7c859f10a103dba68a0a", }, ], // Eager, unlike the two codecs above. A codec that is never asked for should diff --git a/crates/openhuman-core/src/platform/about_app/catalog_conversation_intelligence.rs b/crates/openhuman-core/src/platform/about_app/catalog_conversation_intelligence.rs index 11ca9593838..aedab426c21 100644 --- a/crates/openhuman-core/src/platform/about_app/catalog_conversation_intelligence.rs +++ b/crates/openhuman-core/src/platform/about_app/catalog_conversation_intelligence.rs @@ -347,7 +347,7 @@ Capability { name: "Memory Engine", domain: "intelligence", category: CapabilityCategory::Intelligence, - description: "Choose which engine stores and recalls the assistant's memory: the built-in local TinyCortex (default), CortexDB hosted by TinyHumans (billed in credits, uses your signed-in session), or your own Supermemory, Mem0, Cognee, CortexDB or AgentMemory service. Switching applies immediately without a restart, and existing memories can be copied to the new engine first. Keys live in the OS keychain, never in config. Local-only capabilities such as the memory tree and document store are only available on the local engine.", + description: "Choose which engine stores and recalls the assistant's memory: the built-in local TinyCortex (default), CortexDB hosted by TinyHumans (billed in credits, uses your signed-in session), or your own Supermemory, Mem0, Cognee, CortexDB or AgentMemory service. Switching applies immediately without a restart, and existing memories can be copied to the new engine first. Keys live in the OS keychain, never in config. Hosted memory also keeps documents, goals, tool rules, the learned profile and episodic memory, takes connector and local-folder syncs, and draws the Brain graph from what the server understood; the local chunk store and its tools (vault, pipeline status, tree rebuild) are only available on the local engine, and other remote engines keep the core memory only.", how_to: "Settings > Memory Engine. Pick an engine, enter its endpoint and key if it needs them, then switch or migrate.", status: CapabilityStatus::Beta, privacy: MEMORY_TO_REMOTE_ENGINE, diff --git a/crates/openhuman-core/src/platform/connectivity/schemas_tests.rs b/crates/openhuman-core/src/platform/connectivity/schemas_tests.rs index b64c7bef595..29e53e67799 100644 --- a/crates/openhuman-core/src/platform/connectivity/schemas_tests.rs +++ b/crates/openhuman-core/src/platform/connectivity/schemas_tests.rs @@ -28,13 +28,6 @@ fn diag_schema_outputs_a_diag_payload_field() { assert_eq!(s.outputs[0].name, "diag"); } -#[test] -fn unknown_function_returns_unknown_fallback() { - let s = schemas("no_such"); - assert_eq!(s.function, "unknown"); - assert_eq!(s.namespace, "connectivity"); -} - #[tokio::test] async fn handle_diag_returns_json_object() { let value = handle_diag(Map::new()).await.expect("diag handler ok"); diff --git a/crates/openhuman-core/src/platform/cost/schemas_tests.rs b/crates/openhuman-core/src/platform/cost/schemas_tests.rs index 0d1a7d956c2..befab54bfaf 100644 --- a/crates/openhuman-core/src/platform/cost/schemas_tests.rs +++ b/crates/openhuman-core/src/platform/cost/schemas_tests.rs @@ -60,13 +60,6 @@ fn schema_for_usage_log_has_days_and_limit_inputs() { assert_eq!(s.outputs[0].name, "usage_log"); } -#[test] -fn schema_for_unknown_returns_error_shape() { - let s = schema_for("cost_get_nonexistent"); - assert_eq!(s.function, "unknown"); - assert_eq!(s.outputs[0].name, "error"); -} - #[test] fn new_correlation_id_returns_eight_hex_chars() { let cid = new_correlation_id(); diff --git a/crates/openhuman-core/src/platform/doctor/schemas_tests.rs b/crates/openhuman-core/src/platform/doctor/schemas_tests.rs index ddbf0d5c270..3a8e21e5eb1 100644 --- a/crates/openhuman-core/src/platform/doctor/schemas_tests.rs +++ b/crates/openhuman-core/src/platform/doctor/schemas_tests.rs @@ -26,12 +26,6 @@ fn models_schema_has_optional_use_cache() { assert!(use_cache.is_some_and(|f| !f.required)); } -#[test] -fn unknown_function_returns_unknown() { - let s = schemas("nonexistent"); - assert_eq!(s.function, "unknown"); -} - #[test] fn schemas_and_controllers_match() { let s = all_controller_schemas(); diff --git a/crates/openhuman-core/src/platform/health/schemas_tests.rs b/crates/openhuman-core/src/platform/health/schemas_tests.rs index 235e9c203cb..2233c024d86 100644 --- a/crates/openhuman-core/src/platform/health/schemas_tests.rs +++ b/crates/openhuman-core/src/platform/health/schemas_tests.rs @@ -29,13 +29,6 @@ fn system_info_schema() { assert_eq!(s.outputs.len(), 4); } -#[test] -fn unknown_function_returns_unknown() { - let s = schemas("bad"); - assert_eq!(s.function, "unknown"); - assert_eq!(s.namespace, "health"); -} - #[test] fn schemas_and_controllers_match() { let s = all_controller_schemas(); diff --git a/crates/openhuman-core/src/platform/service/schemas_tests.rs b/crates/openhuman-core/src/platform/service/schemas_tests.rs index 882fb26cb77..7f0a34c558d 100644 --- a/crates/openhuman-core/src/platform/service/schemas_tests.rs +++ b/crates/openhuman-core/src/platform/service/schemas_tests.rs @@ -60,13 +60,6 @@ fn daemon_host_set_requires_show_tray() { assert!(s.inputs[0].required); } -#[test] -fn unknown_function_returns_unknown() { - let s = schemas("nonexistent"); - assert_eq!(s.function, "unknown"); - assert_eq!(s.namespace, "service"); -} - #[test] fn schemas_and_controllers_match() { let s = all_controller_schemas(); diff --git a/crates/openhuman-core/src/platform/socket/schemas_tests.rs b/crates/openhuman-core/src/platform/socket/schemas_tests.rs index 7957959d968..b05c7bfc1ed 100644 --- a/crates/openhuman-core/src/platform/socket/schemas_tests.rs +++ b/crates/openhuman-core/src/platform/socket/schemas_tests.rs @@ -12,13 +12,6 @@ fn catalog_lists_all_five_controllers() { assert!(names.contains(&"connect_with_session")); } -#[test] -fn registered_controllers_match_schemas_count() { - let schemas = all_controller_schemas(); - let handlers = all_registered_controllers(); - assert_eq!(schemas.len(), handlers.len()); -} - #[test] fn all_schemas_use_socket_namespace() { for s in all_controller_schemas() { @@ -60,15 +53,6 @@ fn emit_schema_data_is_optional() { assert!(!data.required); } -#[test] -fn unknown_function_returns_unknown_fallback_schema() { - let s = schemas("no_such_fn"); - assert_eq!(s.namespace, "socket"); - assert_eq!(s.function, "unknown"); - assert_eq!(s.outputs.len(), 1); - assert_eq!(s.outputs[0].name, "error"); -} - #[test] fn every_schema_has_at_least_one_output_field() { for s in all_controller_schemas() { diff --git a/crates/openhuman-core/src/platform/update/schemas_tests.rs b/crates/openhuman-core/src/platform/update/schemas_tests.rs index 1f0cd0d2f5c..d406c7be62d 100644 --- a/crates/openhuman-core/src/platform/update/schemas_tests.rs +++ b/crates/openhuman-core/src/platform/update/schemas_tests.rs @@ -58,13 +58,6 @@ fn apply_schema_has_optional_staging_dir() { assert!(staging.is_some_and(|f| !f.required)); } -#[test] -fn unknown_function_returns_unknown() { - let s = schemas("nonexistent"); - assert_eq!(s.function, "unknown"); - assert_eq!(s.namespace, "update"); -} - #[test] fn schemas_and_controllers_match() { let s = all_controller_schemas(); diff --git a/crates/openhuman-core/src/security/approval/redact_tests.rs b/crates/openhuman-core/src/security/approval/redact_tests.rs index d2bf06ce909..7a050efc7be 100644 --- a/crates/openhuman-core/src/security/approval/redact_tests.rs +++ b/crates/openhuman-core/src/security/approval/redact_tests.rs @@ -336,3 +336,58 @@ fn summarize_action_skill_install_without_entry_id_falls_back() { assert!(summary.contains("skill_registry_install")); assert!(summary.contains("bytes")); } + +#[test] +fn non_string_sensitive_values_redact_to_kind_markers_and_nested_values_recurse() { + let args = json!({ + "metadata": { + "Subject": "Confidential subject", + "auth": true, + "message": 42, + "password": null, + "user": { "id": "user-123", "name": "Alice" }, + "attempts": 3, + "safe_list": [ + "open /Users/frank/Desktop/report.txt", + { "content": "nested secret" } + ] + } + }); + let red = redact_args(&args); + assert_eq!( + red.pointer("/metadata/Subject"), + Some(&json!("")) + ); + assert_eq!(red.pointer("/metadata/attempts"), Some(&json!(3))); + assert_eq!( + red.pointer("/metadata/auth"), + Some(&json!("")) + ); + assert_eq!( + red.pointer("/metadata/message"), + Some(&json!("")) + ); + assert_eq!( + red.pointer("/metadata/password"), + Some(&serde_json::Value::Null) + ); + assert_eq!( + red.pointer("/metadata/user"), + Some(&json!("")) + ); + assert_eq!( + red.pointer("/metadata/safe_list/0"), + Some(&json!("open /Desktop/report.txt")) + ); + assert_eq!( + red.pointer("/metadata/safe_list/1/content"), + Some(&json!("")) + ); + assert_eq!( + redact_args(&json!( + "open /home/carol/report.md and C:\\Users\\dave\\x.txt" + )), + json!("open /report.md and \\x.txt") + ); + assert_eq!(redact_args(&json!("/Users/erin")), json!("")); +} diff --git a/crates/openhuman-core/src/security/approval/schemas_tests.rs b/crates/openhuman-core/src/security/approval/schemas_tests.rs index 3ed568a2179..8b1686ec95d 100644 --- a/crates/openhuman-core/src/security/approval/schemas_tests.rs +++ b/crates/openhuman-core/src/security/approval/schemas_tests.rs @@ -18,13 +18,6 @@ fn schemas_decide_requires_request_id_and_decision() { assert!(s.inputs.iter().all(|f| f.required)); } -#[test] -fn schemas_unknown_returns_placeholder() { - let s = schemas("nope"); - assert_eq!(s.function, "unknown"); - assert_eq!(s.outputs[0].name, "error"); -} - #[test] fn all_registered_controllers_has_handler_per_schema() { let controllers = all_registered_controllers(); diff --git a/crates/openhuman-core/src/security/approval/store_persistence_tests.rs b/crates/openhuman-core/src/security/approval/store_persistence_tests.rs index 68705ba15be..96f251e9906 100644 --- a/crates/openhuman-core/src/security/approval/store_persistence_tests.rs +++ b/crates/openhuman-core/src/security/approval/store_persistence_tests.rs @@ -633,3 +633,34 @@ fn list_pending_for_flow_run_filters_to_the_matching_flow_and_run() { assert_eq!(rows.len(), 1); assert_eq!(rows[0].request_id, "a"); } + +#[test] +fn list_recent_decisions_marks_unparseable_args_instead_of_failing() { + let (config, _dir) = test_config(); + insert_pending(&config, &sample("corrupt-json", "sess-A"), "sess-A").unwrap(); + with_connection(&config, |conn| { + conn.execute( + "UPDATE pending_approvals + SET args_redacted = ?1, decided_at = ?2, decision = ?3 + WHERE request_id = ?4", + params![ + "{not valid json", + Utc::now().to_rfc3339(), + ApprovalDecision::Deny.as_str(), + "corrupt-json" + ], + )?; + Ok(()) + }) + .unwrap(); + + let rows = list_recent_decisions(&config, 10).unwrap(); + let row = rows + .iter() + .find(|row| row.request_id == "corrupt-json") + .expect("corrupt audit row is still listed"); + assert_eq!( + row.args_redacted, + json!({ "_error": "args_redacted not valid JSON" }) + ); +} diff --git a/crates/openhuman-core/src/security/credentials/schemas_tests.rs b/crates/openhuman-core/src/security/credentials/schemas_tests.rs index 428033255f7..b76421699c6 100644 --- a/crates/openhuman-core/src/security/credentials/schemas_tests.rs +++ b/crates/openhuman-core/src/security/credentials/schemas_tests.rs @@ -2,20 +2,6 @@ use super::*; // ── Schema catalog coverage ──────────────────────────────────── -#[test] -fn catalog_counts_match() { - let schemas = all_controller_schemas(); - let handlers = all_registered_controllers(); - assert_eq!(schemas.len(), handlers.len()); - // The account-bound `auth.oauth_*` (including `oauth_fetch_client_key`) / - // `auth.create_channel_link_token` controllers moved to - // `openhuman-tinyhumans`; the core keeps the rest. - assert!( - schemas.len() >= 7, - "auth namespace should expose ≥7 core fns" - ); -} - #[test] fn all_schemas_use_auth_namespace_and_have_descriptions() { for s in all_controller_schemas() { @@ -29,13 +15,6 @@ fn all_schemas_use_auth_namespace_and_have_descriptions() { } } -#[test] -fn unknown_function_returns_unknown_fallback() { - let s = schemas("no_such_fn"); - assert_eq!(s.function, "unknown"); - assert_eq!(s.namespace, "auth"); -} - #[test] fn every_registered_function_has_nonempty_schema_metadata() { for handler in all_registered_controllers() { diff --git a/crates/openhuman-core/src/security/devices/schemas_tests.rs b/crates/openhuman-core/src/security/devices/schemas_tests.rs index 1611f94b047..d41ac6455c0 100644 --- a/crates/openhuman-core/src/security/devices/schemas_tests.rs +++ b/crates/openhuman-core/src/security/devices/schemas_tests.rs @@ -31,13 +31,6 @@ fn schemas_revoke_requires_channel_id() { assert_eq!(s.outputs[0].name, "success"); } -#[test] -fn schemas_unknown_returns_error_placeholder() { - let s = schemas("does-not-exist"); - assert_eq!(s.function, "unknown"); - assert_eq!(s.outputs[0].name, "error"); -} - #[test] fn all_controller_schemas_covers_three_functions() { let names: Vec<_> = all_controller_schemas() @@ -47,14 +40,6 @@ fn all_controller_schemas_covers_three_functions() { assert_eq!(names, vec!["create_pairing", "list", "revoke"]); } -#[test] -fn all_registered_controllers_has_handler_per_schema() { - let controllers = all_registered_controllers(); - assert_eq!(controllers.len(), 3); - let names: Vec<_> = controllers.iter().map(|c| c.schema.function).collect(); - assert_eq!(names, vec!["create_pairing", "list", "revoke"]); -} - #[test] fn read_required_errors_when_key_missing() { let params = Map::new(); diff --git a/crates/openhuman-core/src/security/encryption/schemas_tests.rs b/crates/openhuman-core/src/security/encryption/schemas_tests.rs index e2e9a367dfe..f8ceed53faf 100644 --- a/crates/openhuman-core/src/security/encryption/schemas_tests.rs +++ b/crates/openhuman-core/src/security/encryption/schemas_tests.rs @@ -30,13 +30,6 @@ fn decrypt_schema_requires_ciphertext() { assert_eq!(s.inputs[0].name, "ciphertext"); } -#[test] -fn unknown_function_returns_unknown() { - let s = schemas("nonexistent"); - assert_eq!(s.function, "unknown"); - assert_eq!(s.namespace, "encryption"); -} - #[test] fn schemas_and_controllers_match() { let s = all_controller_schemas(); diff --git a/crates/openhuman-core/src/security/keyring/keyring_tests.rs b/crates/openhuman-core/src/security/keyring/keyring_tests.rs index 71dee7072d1..d77d4d542a0 100644 --- a/crates/openhuman-core/src/security/keyring/keyring_tests.rs +++ b/crates/openhuman-core/src/security/keyring/keyring_tests.rs @@ -465,135 +465,7 @@ fn get_or_create_random_idempotent_file_backend() { assert_eq!(first, second, "idempotent read-back"); } -// ── is_available probe: idempotency regression tests ───────────────────────── -// -// The probe in `is_available()` must return `true` on every launch, not just the -// first one. Before the fix, `set()` was called blindly: on macOS the Keychain -// returns `-25299 "item already exists"` when the probe key survives from a -// prior launch, flipping `is_available` to `false` even though the keychain is -// fully functional. The fix deletes the probe key first so the write always -// lands clean. -// -// We verify this with a `StrictSetBackend` — a `FileBackend` wrapper that -// rejects `set()` on an already-existing key, exactly matching the Keychain -// semantics that exposed the bug. This lets the regression run in CI without -// the `OPENHUMAN_TEST_OS_KEYCHAIN=1` gate. - -/// Wraps `FileBackend` but fails `set` with `KeyringError::Backend` when the -/// key already exists, mirroring macOS Keychain's `-25299` behaviour. -struct StrictSetBackend { - inner: FileBackend, -} - -impl StrictSetBackend { - fn new(dir: &std::path::Path) -> Self { - Self { - inner: FileBackend::new(dir), - } - } -} - -impl KeyringBackend for StrictSetBackend { - fn get(&self, key: &str) -> Result, KeyringError> { - self.inner.get(key) - } - fn set(&self, key: &str, value: &str) -> Result<(), KeyringError> { - if self.inner.get(key)?.is_some() { - return Err(KeyringError::Backend( - "Platform secure storage failure: The specified item already exists in the keychain. (OSStatus -25299)".into(), - )); - } - self.inner.set(key, value) - } - fn delete(&self, key: &str) -> Result<(), KeyringError> { - self.inner.delete(key) - } - fn name(&self) -> &'static str { - "strict-set-mock" - } -} - -/// Run the OLD (broken) probe logic against any backend. -/// Returns `true` only if the round-trip succeeded. -fn old_probe(b: &B) -> bool { - const KEY: &str = "__probe__:__openhuman_keyring_probe__"; - const VAL: &str = "__probe_value__"; - if b.set(KEY, VAL).is_err() { - return false; - } - let ok = b.get(KEY).ok().flatten().as_deref() == Some(VAL); - let _ = b.delete(KEY); - ok -} - -/// Run the NEW (fixed) probe logic against any backend. -/// Deletes any residue before writing, making the probe idempotent. -fn new_probe(b: &B) -> bool { - const KEY: &str = "__probe__:__openhuman_keyring_probe__"; - const VAL: &str = "__probe_value__"; - let _ = b.delete(KEY); - if b.set(KEY, VAL).is_err() { - return false; - } - let ok = b.get(KEY).ok().flatten().as_deref() == Some(VAL); - let _ = b.delete(KEY); - ok -} - -#[test] -fn probe_old_logic_fails_when_key_preexists() { - // Demonstrates the bug: old probe returns false the second time because - // `set` on an already-existing key fails with "item already exists". - let dir = TempDir::new().expect("tempdir"); - let b = StrictSetBackend::new(dir.path()); - - // First probe: key absent → succeeds. - assert!(old_probe(&b), "first probe should succeed"); - - // Key was deleted by the probe — re-seed it to simulate a leftover from a - // previous launch (e.g. the app was force-quit after writing but before - // the delete could run, or a previous `is_available` call left it behind). - b.inner - .set("__probe__:__openhuman_keyring_probe__", "stale") - .unwrap(); - - // Second probe with residue: `set` hits "already exists" → returns false. - assert!( - !old_probe(&b), - "old probe must fail when probe key pre-exists (regression target)" - ); -} - -#[test] -fn probe_new_logic_succeeds_even_when_key_preexists() { - // Verifies the fix: new probe deletes any residue first, so it always - // succeeds regardless of leftover state. - let dir = TempDir::new().expect("tempdir"); - let b = StrictSetBackend::new(dir.path()); - - assert!(new_probe(&b), "first probe should succeed"); - - // Re-seed to simulate a leftover key (same scenario as the bug test). - b.inner - .set("__probe__:__openhuman_keyring_probe__", "stale") - .unwrap(); - - assert!( - new_probe(&b), - "new probe must succeed even when probe key pre-exists" - ); -} - -#[test] -fn probe_new_logic_is_idempotent_across_multiple_runs() { - // New probe must return true on every consecutive call. - let dir = TempDir::new().expect("tempdir"); - let b = StrictSetBackend::new(dir.path()); - - for i in 0..5 { - assert!(new_probe(&b), "probe run {i} should succeed"); - } -} +// ── is_available probe: idempotency (OS backend only) ───────────────────────── #[test] fn is_available_returns_true_on_repeated_calls_os_backend() { diff --git a/crates/openhuman-core/src/security/policy/path_checks.rs b/crates/openhuman-core/src/security/policy/path_checks.rs index 29f686a4d13..2ce92958193 100644 --- a/crates/openhuman-core/src/security/policy/path_checks.rs +++ b/crates/openhuman-core/src/security/policy/path_checks.rs @@ -1,7 +1,10 @@ use std::path::{Path, PathBuf}; use super::types::{SecurityPolicy, TrustedAccess, POLICY_BLOCKED_MARKER}; -use super::types::{WORKSPACE_INTERNAL_DIRS, WORKSPACE_INTERNAL_FILES}; +use super::types::{ + ACCOUNT_CONFIG_FILE, ARTIFACTS_DIR, ARTIFACT_TOOL_RESULTS_DIR, WORKSPACE_INTERNAL_DIRS, + WORKSPACE_INTERNAL_FILES, +}; impl SecurityPolicy { /// Expand a leading `~/` to the user's home directory. Delegates to @@ -391,6 +394,16 @@ impl SecurityPolicy { (Ok(w), Ok(p)) => (w.as_path(), p.as_path()), _ => (self.workspace_dir.as_path(), path), }; + // The account config (`/config.toml`, the workspace's + // sibling) holds the autonomy policy itself and the files folders the + // artifact escape guard trusts (`files_dir_override`, + // `files_dir_history`, #5505). A trusted root over the account or data + // dir must not let the agent rewrite either. + if let Some(account_dir) = ws.parent() { + if check_path == account_dir.join(ACCOUNT_CONFIG_FILE) { + return true; + } + } if !check_path.starts_with(ws) { return false; } @@ -414,6 +427,18 @@ impl SecurityPolicy { { return true; } + // Artifact metadata (#5505): `artifacts//meta.json` names the file + // an artifact owns and Download / `read_artifact_bytes` follow it, so + // every per-artifact directory is internal state. `artifacts/tool- + // results/` is not: the agent reads its own large tool outputs back + // from there. + if component == ARTIFACTS_DIR { + if let Some(std::path::Component::Normal(second)) = relative.components().nth(1) { + if second != ARTIFACT_TOOL_RESULTS_DIR { + return true; + } + } + } // Check single-file entries (only if the relative path is exactly one component) if relative.components().count() == 1 && WORKSPACE_INTERNAL_FILES diff --git a/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs b/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs index 8082d0ad4cf..b01c572d603 100644 --- a/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs +++ b/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs @@ -91,6 +91,47 @@ fn is_path_string_allowed_blocks_workspace_internal() { ); } +/// #5505: an artifact's `meta.json` / `args.json` name the file Download and +/// `read_artifact_bytes` follow, so the agent's file tools must not write them +/// even through a trusted root that reaches the workspace, while the +/// `artifacts/tool-results/` read-back stays reachable. +#[tokio::test] +async fn artifact_metadata_is_internal_but_tool_results_are_not() { + let tmp = tempfile::tempdir().expect("tempdir"); + let ws = tmp.path().join("workspace"); + let record = ws.join("artifacts").join("abc"); + let results = ws.join("artifacts").join("tool-results").join("s1"); + std::fs::create_dir_all(&record).expect("create record dir"); + std::fs::create_dir_all(&results).expect("create tool-results dir"); + std::fs::write(record.join("meta.json"), "{}").expect("write meta"); + std::fs::write(results.join("call-1.txt"), "output").expect("write result"); + let policy = SecurityPolicy { + workspace_dir: ws.clone(), + action_dir: ws.clone(), + workspace_only: false, + trusted_roots: vec![TrustedRoot { + path: ws.to_string_lossy().into_owned(), + access: TrustedAccess::ReadWrite, + }], + ..SecurityPolicy::default() + }; + + let meta = record.join("meta.json"); + assert!(!policy.is_path_string_allowed(&meta.to_string_lossy())); + assert!(policy.validate_path(&meta.to_string_lossy()).await.is_err()); + assert!(policy + .validate_parent_path(&record.join("args.json").to_string_lossy()) + .await + .is_err()); + + let result = results.join("call-1.txt"); + assert!(policy.is_path_string_allowed(&result.to_string_lossy())); + assert!(policy + .validate_path(&result.to_string_lossy()) + .await + .is_ok()); +} + #[tokio::test] async fn trusted_root_cannot_expose_workspace_internal_state() { let tmp = tempfile::tempdir().expect("tempdir"); @@ -201,3 +242,40 @@ async fn the_turn_root_grant_never_reaches_a_credential_store() { "unexpected error: {err}" ); } + +/// #5505: the account config beside the workspace holds the autonomy policy +/// and the files folders the artifact escape guard trusts, so a trusted root +/// over the account dir must not make it readable or writable, while other +/// files there stay reachable. +#[tokio::test] +async fn the_account_config_beside_the_workspace_is_internal() { + let tmp = tempfile::tempdir().expect("tempdir"); + let account = tmp.path().join("users").join("u1"); + let ws = account.join("workspace"); + std::fs::create_dir_all(&ws).expect("create workspace"); + let config = account.join("config.toml"); + std::fs::write(&config, "files_dir_history = []").expect("write config"); + let notes = account.join("notes.txt"); + std::fs::write(¬es, "hello").expect("write notes"); + let policy = SecurityPolicy { + workspace_dir: ws.clone(), + action_dir: ws.clone(), + workspace_only: false, + trusted_roots: vec![TrustedRoot { + path: account.to_string_lossy().into_owned(), + access: TrustedAccess::ReadWrite, + }], + ..SecurityPolicy::default() + }; + + assert!(!policy.is_path_string_allowed(&config.to_string_lossy())); + assert!(policy + .validate_path(&config.to_string_lossy()) + .await + .is_err()); + assert!(policy + .validate_parent_path(&config.to_string_lossy()) + .await + .is_err()); + assert!(policy.validate_path(¬es.to_string_lossy()).await.is_ok()); +} diff --git a/crates/openhuman-core/src/security/policy/types.rs b/crates/openhuman-core/src/security/policy/types.rs index 480ff42d771..b1ffd5a8fd2 100644 --- a/crates/openhuman-core/src/security/policy/types.rs +++ b/crates/openhuman-core/src/security/policy/types.rs @@ -190,6 +190,16 @@ pub(super) const WORKSPACE_INTERNAL_DIRS: &[&str] = &[ "tinyplace", ]; +/// The artifact store under `workspace_dir`. Its per-artifact directories are +/// internal state (see `is_workspace_internal_path`); only +/// [`ARTIFACT_TOOL_RESULTS_DIR`] inside it stays agent-readable. +pub(super) const ARTIFACTS_DIR: &str = "artifacts"; +/// The account config file, stored beside `workspace_dir` (see +/// `is_workspace_internal_path`). +pub(super) const ACCOUNT_CONFIG_FILE: &str = "config.toml"; +/// Where oversized tool outputs are persisted for the agent to read back. +pub(super) const ARTIFACT_TOOL_RESULTS_DIR: &str = "tool-results"; + /// Files directly under `workspace_dir` that hold secrets or persona config /// and must not be writable by agent tools. pub(super) const WORKSPACE_INTERNAL_FILES: &[&str] = &[ diff --git a/crates/openhuman-core/src/skills/README.md b/crates/openhuman-core/src/skills/README.md index efbf2ad2b10..c5f2d444170 100644 --- a/crates/openhuman-core/src/skills/README.md +++ b/crates/openhuman-core/src/skills/README.md @@ -80,7 +80,7 @@ Plus the sub-domain namespaces: `skill_registry.*` (`browse`, `search`, `sources Behavior tests live beside their modules as `*_tests.rs` (for example `ops_tests.rs` and its `ops_discovery_tests.rs`, `ops_create_and_url_tests.rs`, `ops_uninstall_tests.rs` siblings, `ops_create_render_skill_toml_tests_tests.rs`, `ops_discover_include_skills_tests_tests.rs`, `ops_install_install_fetch_tests_tests.rs`, `preflight_tests.rs`, `registry_tests.rs`, `run_log_tests.rs`, `schemas_tests.rs`, `search_tests.rs`, `tools_tests.rs`, `types_tests.rs`, `bus_tests.rs`), wired via `#[path]` from the module they cover. -`e2e_plumbing_tests.rs` and `e2e_run_tests.rs` are mock-LLM end-to-end tests: plumbing (create then registry round-trip, an orchestrator turn calling `list_workflows`/`run_workflow`, `await_run_outcome` polling) and run execution (`spawn_workflow_run_background` through a terminal `DONE` to `await_run_outcome`, marked `#[ignore]` and run serially because they set the process-global `OPENHUMAN_WORKSPACE`). +`e2e_plumbing_tests.rs` is the mock-LLM end-to-end test: create then registry round-trip, an orchestrator turn calling `list_workflows`/`run_workflow`, and `await_run_outcome` polling. Catalog refresh in a live session (`refresh_workflows`) is covered by `crates/openhuman-core/src/agent/session_host/session_builder_and_listener_tests.rs`. diff --git a/crates/openhuman-core/src/skills/catalog/ops_tests.rs b/crates/openhuman-core/src/skills/catalog/ops_tests.rs index 5f160cd8cd8..9d1d40f7666 100644 --- a/crates/openhuman-core/src/skills/catalog/ops_tests.rs +++ b/crates/openhuman-core/src/skills/catalog/ops_tests.rs @@ -14,35 +14,6 @@ fn same_named_catalog() -> Vec { .collect() } -fn find_catalog_entry_matches_ids_and_unambiguous_legacy_names() { - let catalog = same_named_catalog(); - let by_id = find_catalog_entry(&catalog, "clawhub/ai-code-review-ops").unwrap(); - assert_eq!(by_id.id, "clawhub/ai-code-review-ops"); - // An exact id wins over another entry carrying the same name. - assert_eq!( - find_catalog_entry(&catalog, "apple-notes").unwrap().source, - "built-in" - ); - // Ids used to be display names; a name only one entry has still resolves. - assert_eq!( - find_catalog_entry(&catalog, "Apple Design").unwrap().id, - "clawhub/apple-design" - ); -} - -#[test] -fn find_catalog_entry_refuses_an_ambiguous_name_and_lists_the_ids() { - let err = find_catalog_entry(&same_named_catalog(), "AI Code Review").unwrap_err(); - assert!( - err.contains("2 catalog entries are named 'AI Code Review'"), - "{err}" - ); - assert!( - err.contains("clawhub/qf-code-review") && err.contains("clawhub/ai-code-review-ops"), - "{err}" - ); -} - #[test] fn find_catalog_entry_not_found_suggests_real_ids_instead_of_a_refresh() { let err = find_catalog_entry(&same_named_catalog(), "ai-code-review").unwrap_err(); @@ -79,12 +50,6 @@ async fn install_from_catalog_errors_for_portal_skill_without_download() { ); } -#[test] -fn parse_catalog_json_rejects_invalid_payloads() { - let error = parse_catalog_json("{").expect_err("invalid json"); - assert!(error.contains("invalid catalog json")); -} - #[test] fn refresh_on_boot_enabled_defaults_on_and_accepts_common_false_values() { assert!(refresh_on_boot_enabled(None)); diff --git a/crates/openhuman-core/src/skills/e2e_run_tests.rs b/crates/openhuman-core/src/skills/e2e_run_tests.rs deleted file mode 100644 index ac3a84ce47d..00000000000 --- a/crates/openhuman-core/src/skills/e2e_run_tests.rs +++ /dev/null @@ -1,202 +0,0 @@ -//! Mocked-LLM e2e tests for generic workflow-run plumbing. -//! -//! These ignored, serial tests cover two generic workflow behaviours: an inner -//! workflow reaches a -//! terminal footer and an orchestrator consumes that result via `run_workflow`. - -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; -use std::time::Duration; - -use async_trait::async_trait; - -use crate::agent::harness::run_channel_turn_via_graph; -use crate::agent::messages::ChatMessage; -use crate::agent::tools::RunWorkflowTool; -use crate::config::{MultimodalConfig, MultimodalFileConfig}; -use crate::inference::provider::factory::test_provider_override; -use crate::skills::runtime::{await_run_outcome, spawn_workflow_run_background}; -use tinyinference_llm::message::AssistantMessage; -use tinyinference_llm::model::{ChatModel, ModelProfile, ModelRequest, ModelResponse}; -use tinyinference_llm::tool::ToolCall; -use tinytools::Tool; - -fn serial() -> &'static tokio::sync::Mutex<()> { - static LOCK: std::sync::OnceLock> = std::sync::OnceLock::new(); - LOCK.get_or_init(|| tokio::sync::Mutex::new(())) -} - -struct WorkspaceEnv { - previous: Option, -} - -impl WorkspaceEnv { - fn set(path: &std::path::Path) -> Self { - let previous = std::env::var("OPENHUMAN_WORKSPACE").ok(); - std::env::set_var("OPENHUMAN_WORKSPACE", path); - Self { previous } - } -} - -impl Drop for WorkspaceEnv { - fn drop(&mut self) { - match &self.previous { - Some(value) => std::env::set_var("OPENHUMAN_WORKSPACE", value), - None => std::env::remove_var("OPENHUMAN_WORKSPACE"), - } - } -} - -struct MockLlm { - workflow_id: Option, - workflow_call_emitted: AtomicBool, -} - -impl MockLlm { - fn new(workflow_id: Option<&str>) -> Arc { - Arc::new(Self { - workflow_id: workflow_id.map(str::to_owned), - workflow_call_emitted: AtomicBool::new(false), - }) - } -} - -fn final_text(text: &str) -> ModelResponse { - ModelResponse::assistant(text) -} - -fn tool_call_response(id: &str, name: &str, arguments: serde_json::Value) -> ModelResponse { - ModelResponse { - message: AssistantMessage { - id: None, - content: Vec::new(), - tool_calls: vec![ToolCall::new(id, name, arguments)], - usage: None, - origin: None, - }, - usage: None, - finish_reason: Some("tool_calls".to_string()), - raw: None, - resolved_model: None, - continue_turn: None, - served_from_cache: false, - correlation: None, - resolved_route: None, - } -} - -#[async_trait] -impl ChatModel<()> for MockLlm { - async fn invoke( - &self, - _state: &(), - request: ModelRequest, - ) -> tinyinference_llm::Result { - let conversation = request - .messages - .iter() - .map(|message| message.text()) - .collect::>() - .join("\n"); - if conversation.contains("running a single workflow") - || conversation.contains("Workflow guidelines") - { - return Ok(final_text("WORKFLOW_DONE: inbox triaged")); - } - if conversation.contains("WORKFLOW_DONE") || conversation.contains("\"status\"") { - return Ok(final_text("ORCHESTRATOR_DONE")); - } - match &self.workflow_id { - Some(id) if !self.workflow_call_emitted.swap(true, Ordering::SeqCst) => { - Ok(tool_call_response( - "c1", - "run_workflow", - serde_json::json!({ "workflow_id": id, "wait_seconds": 20 }), - )) - } - Some(_) => Ok(final_text("WORKFLOW_DONE: inbox triaged")), - None => Ok(final_text("TASK_DONE_NO_WORKFLOW")), - } - } -} - -fn seed_runnable_workflow(workspace: &std::path::Path, id: &str) { - let directory = workspace.join("skills").join(id); - std::fs::create_dir_all(&directory).unwrap(); - std::fs::write( - directory.join("skill.toml"), - format!("id = \"{id}\"\nwhen_to_use = \"triage email\"\n"), - ) - .unwrap(); - std::fs::write( - directory.join("SKILL.md"), - format!( - "---\nname: {id}\ndescription: Triage the inbox.\n---\n\nSummarise and label the inbox.\n" - ), - ) - .unwrap(); -} - -#[ignore = "process-global model override + OPENHUMAN_WORKSPACE; run serially"] -#[tokio::test] -async fn inner_workflow_run_executes_via_mock_llm_and_reaches_done() { - let _serial = serial().lock().await; - let workspace_root = tempfile::tempdir().unwrap(); - let _environment = WorkspaceEnv::set(workspace_root.path()); - let workspace = crate::skills::schemas::resolve_workspace_dir().await; - seed_runnable_workflow(&workspace, "triage-inbox"); - let _provider = test_provider_override::install_model(MockLlm::new(Some("triage-inbox"))); - - let started = spawn_workflow_run_background("triage-inbox".to_string(), None) - .await - .expect("runnable workflow should spawn"); - let outcome = await_run_outcome(&started.log_path, Duration::from_secs(20)) - .await - .unwrap_or_else(|| panic!("inner workflow did not reach a terminal footer")); - - assert_eq!(outcome.status, "DONE"); - assert!(outcome.output.contains("WORKFLOW_DONE")); -} - -#[ignore = "process-global model override + OPENHUMAN_WORKSPACE; run serially"] -#[tokio::test] -async fn orchestrator_runs_workflow_tool_and_gets_inner_result() { - let _serial = serial().lock().await; - let workspace_root = tempfile::tempdir().unwrap(); - let _environment = WorkspaceEnv::set(workspace_root.path()); - let workspace = crate::skills::schemas::resolve_workspace_dir().await; - seed_runnable_workflow(&workspace, "triage-inbox"); - let mock = MockLlm::new(Some("triage-inbox")); - let _provider = test_provider_override::install_model(mock.clone()); - let model: Arc> = mock; - let mut profile = ModelProfile::default(); - profile.tool_calling = true; - profile.parallel_tool_calls = true; - let tools: Arc>> = Arc::new(vec![Box::new(RunWorkflowTool::new())]); - let mut history = vec![ChatMessage::user("Triage my inbox.")]; - - let result = run_channel_turn_via_graph( - crate::agent::tinyagents::TurnModelSource::from_model_with_profile(model, profile), - &mut history, - tools, - vec![], - None, - "model", - 0.0, - 5, - MultimodalConfig::default(), - MultimodalFileConfig::default(), - None, - ) - .await - .expect("orchestrator loop should complete"); - - assert_eq!(result.text, "ORCHESTRATOR_DONE"); - let tool_messages = history - .iter() - .filter(|message| message.role == "tool") - .map(|message| message.content.clone()) - .collect::>() - .join("\n"); - assert!(tool_messages.contains("DONE") && tool_messages.contains("WORKFLOW_DONE")); -} diff --git a/crates/openhuman-core/src/skills/mod.rs b/crates/openhuman-core/src/skills/mod.rs index e3b020a1afb..b6a443c49e4 100644 --- a/crates/openhuman-core/src/skills/mod.rs +++ b/crates/openhuman-core/src/skills/mod.rs @@ -78,10 +78,6 @@ pub mod tools; #[path = "e2e_plumbing_tests.rs"] mod e2e_plumbing_tests; -#[cfg(all(test, feature = "skills"))] -#[path = "e2e_run_tests.rs"] -mod e2e_run_tests; - #[cfg(feature = "skills")] pub use ops::*; #[cfg(feature = "skills")] diff --git a/crates/openhuman-core/src/skills/webhooks/schemas_tests.rs b/crates/openhuman-core/src/skills/webhooks/schemas_tests.rs index a23ffff1c56..fd48515d209 100644 --- a/crates/openhuman-core/src/skills/webhooks/schemas_tests.rs +++ b/crates/openhuman-core/src/skills/webhooks/schemas_tests.rs @@ -159,17 +159,6 @@ fn trigger_agent_requires_caller_id_only() { } } -#[test] -fn unknown_function_returns_error_fallback_schema() { - let s = schemas("no_such_fn"); - assert_eq!(s.function, "unknown"); - assert_eq!(s.namespace, "webhooks"); - assert_eq!(s.outputs.len(), 1); - assert_eq!(s.outputs[0].name, "error"); - assert!(matches!(s.outputs[0].ty, TypeSchema::String)); - assert!(s.outputs[0].required); -} - // ── deserialize_params ──────────────────────────────────────── #[test] diff --git a/crates/openhuman-core/src/threads/ops_conversion_tests.rs b/crates/openhuman-core/src/threads/ops_conversion_tests.rs index 125fbbed727..b60ff319781 100644 --- a/crates/openhuman-core/src/threads/ops_conversion_tests.rs +++ b/crates/openhuman-core/src/threads/ops_conversion_tests.rs @@ -24,12 +24,6 @@ fn counts_materialises_entries_as_owned_string_keys() { assert_eq!(map.len(), 2); } -#[test] -fn counts_empty_iter_yields_empty_map() { - let map = counts([]); - assert!(map.is_empty()); -} - // NOTE: the title_log_fingerprint / collapse_whitespace copies were removed // here (plan.md §2.1) — threads/title.rs (the owning module) already covers // these functions with equivalent cases; the lowercase-hex assertion was @@ -108,72 +102,38 @@ fn build_title_prompt_renders_user_and_assistant_sections_in_order() { // ── is_auto_generated_thread_title ──────────────────────────── #[test] -fn is_auto_generated_thread_title_accepts_canonical_new_chat_format() { +fn is_auto_generated_thread_title_accepts_only_the_new_chat_format() { // Parser locks the format produced by `thread_create_new`: - // "Chat AM|PM". - assert!(is_auto_generated_thread_title("Chat Jan 1 1:00 AM")); - assert!(is_auto_generated_thread_title("Chat Dec 31 12:59 PM")); -} - -#[test] -fn is_auto_generated_thread_title_tolerates_surrounding_whitespace() { - // Input is trimmed before parsing — storage layers may round-trip - // titles with stray whitespace. - assert!(is_auto_generated_thread_title(" Chat Jan 1 1:00 AM ")); -} - -#[test] -fn is_auto_generated_thread_title_rejects_user_edited_titles() { - // Any freeform user title must fall through to the "not a - // placeholder" branch so we never overwrite user-authored names. - assert!(!is_auto_generated_thread_title("My custom title")); - assert!(!is_auto_generated_thread_title("Trip planning")); -} - -#[test] -fn is_auto_generated_thread_title_rejects_short_strings() { - // Hard `bytes.len() < 16` guard — locks in the minimum shape so - // we never enter the parser with too-small input. - assert!(!is_auto_generated_thread_title("")); - assert!(!is_auto_generated_thread_title("Chat")); - assert!(!is_auto_generated_thread_title("Chat Jan 1")); -} - -#[test] -fn is_auto_generated_thread_title_rejects_non_alpha_month() { - // Month abbreviation must be 3 ASCII alpha chars. - assert!(!is_auto_generated_thread_title("Chat 123 1 1:00 AM")); -} - -#[test] -fn is_auto_generated_thread_title_rejects_long_month_name() { - // "January 1 1:00 AM" — after "Chat ", bytes[8] is 'u' not ' '. - assert!(!is_auto_generated_thread_title("Chat January 1 1:00 AM")); -} - -#[test] -fn is_auto_generated_thread_title_rejects_three_digit_day() { - // day: 1–2 ASCII digits; idx-day_start>2 rejects. - assert!(!is_auto_generated_thread_title("Chat Jan 100 1:00 AM")); -} - -#[test] -fn is_auto_generated_thread_title_rejects_missing_colon() { - // 3-digit hour consumes through the position the `:` must occupy. - assert!(!is_auto_generated_thread_title("Chat Jan 1 100 AM")); -} - -#[test] -fn is_auto_generated_thread_title_rejects_lowercase_meridiem() { - // Parser only accepts "AM" | "PM" (not "am"/"pm") so pattern stays - // tied to the producer in `thread_create_new`. - assert!(!is_auto_generated_thread_title("Chat Jan 1 1:00 am")); -} - -#[test] -fn is_auto_generated_thread_title_rejects_missing_space_before_meridiem() { - // The `bytes[idx + 2] != b' '` guard must reject "1:00AM" (no space). - assert!(!is_auto_generated_thread_title("Chat Jan 1 1:00AM")); + // "Chat AM|PM". Input is trimmed before parsing. + for title in [ + "Chat Jan 1 1:00 AM", + "Chat Dec 31 12:59 PM", + " Chat Jan 1 1:00 AM ", + ] { + assert!(is_auto_generated_thread_title(title), "{title:?}"); + } + // Everything else must fall through so user-authored names are never + // overwritten. + for title in [ + "My custom title", + "Trip planning", + // `bytes.len() < 16` guard + "", + "Chat", + "Chat Jan 1", + // month must be 3 ASCII alpha chars + "Chat 123 1 1:00 AM", + "Chat January 1 1:00 AM", + // day is 1-2 digits + "Chat Jan 100 1:00 AM", + // hour/colon shape + "Chat Jan 1 100 AM", + // meridiem is exactly "AM" | "PM", preceded by a space + "Chat Jan 1 1:00 am", + "Chat Jan 1 1:00AM", + ] { + assert!(!is_auto_generated_thread_title(title), "{title:?}"); + } } // ── envelope ────────────────────────────────────────────────── @@ -215,15 +175,6 @@ fn envelope_omits_counts_and_pagination_when_not_provided() { assert!(out.value.meta.pagination.is_none()); } -#[test] -fn envelope_generates_unique_request_ids_per_call() { - // request_id uniqueness matters for client-side correlation of - // overlapping threads-API calls. Lock it in. - let a = envelope(json!({}), None, None); - let b = envelope(json!({}), None, None); - assert_ne!(a.value.meta.request_id, b.value.meta.request_id); -} - #[test] fn thread_to_summary_preserves_all_fields() { let summary = thread_to_summary(sample_thread()); @@ -585,43 +536,24 @@ async fn turn_state_clear_reports_false_when_snapshot_is_absent() { // ── thread_update_title ─────────────────────────────────────── #[tokio::test] -async fn thread_update_title_rejects_empty_title() { +async fn thread_update_title_rejects_empty_and_whitespace_only_titles() { let _env_lock = crate::config::TEST_ENV_LOCK .lock() .unwrap_or_else(|e| e.into_inner()); let workspace = tempfile::tempdir().expect("workspace"); let _workspace_guard = EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", workspace.path()); - let err = thread_update_title(crate::memory::UpdateConversationThreadTitleRequest { - thread_id: "t-1".to_string(), - title: "".to_string(), - }) - .await - .expect_err("empty title must be rejected"); - - assert!( - err.contains("must not be empty"), - "expected empty-title error, got: {err}" - ); -} - -#[tokio::test] -async fn thread_update_title_rejects_whitespace_only_title() { - let _env_lock = crate::config::TEST_ENV_LOCK - .lock() - .unwrap_or_else(|e| e.into_inner()); - let workspace = tempfile::tempdir().expect("workspace"); - let _workspace_guard = EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", workspace.path()); - - let err = thread_update_title(crate::memory::UpdateConversationThreadTitleRequest { - thread_id: "t-1".to_string(), - title: " ".to_string(), - }) - .await - .expect_err("whitespace-only title must be rejected"); + for title in ["", " "] { + let err = thread_update_title(crate::memory::UpdateConversationThreadTitleRequest { + thread_id: "t-1".to_string(), + title: title.to_string(), + }) + .await + .expect_err("blank title must be rejected"); - assert!( - err.contains("must not be empty"), - "expected empty-title error, got: {err}" - ); + assert!( + err.contains("must not be empty"), + "expected empty-title error for {title:?}, got: {err}" + ); + } } diff --git a/crates/openhuman-core/src/tools/impl/document/document_tests.rs b/crates/openhuman-core/src/tools/impl/document/document_tests.rs index 44a0149874c..db52a327b37 100644 --- a/crates/openhuman-core/src/tools/impl/document/document_tests.rs +++ b/crates/openhuman-core/src/tools/impl/document/document_tests.rs @@ -36,7 +36,11 @@ fn test_security(workspace: &Path) -> Arc { } fn make_tool(workspace: &Path) -> DocumentTool { - DocumentTool::new(workspace.to_path_buf(), test_security(workspace)) + DocumentTool::new( + workspace.to_path_buf(), + workspace.join("Files"), + test_security(workspace), + ) } fn minimal_input_json() -> serde_json::Value { diff --git a/crates/openhuman-core/src/tools/impl/document/mod.rs b/crates/openhuman-core/src/tools/impl/document/mod.rs index 753024f37d8..3fddd85825e 100644 --- a/crates/openhuman-core/src/tools/impl/document/mod.rs +++ b/crates/openhuman-core/src/tools/impl/document/mod.rs @@ -71,6 +71,8 @@ pub const TOOL_NAME: &str = "generate_document"; /// One-shot `.docx` generator. See module docs for the request flow. pub struct DocumentTool { workspace_dir: PathBuf, + /// Visible folder the generated document is written into (#5505). + files_dir: crate::agent::artifacts::FileRoots, /// Retained for constructor parity with [`PresentationTool`] (both are /// registered identically in `tools::ops`) and for future features /// (e.g. embedding a `File`-source image) that will need the same @@ -84,12 +86,27 @@ impl DocumentTool { /// directory the artifact pipeline writes into, plus the active /// [`SecurityPolicy`] (same signature as [`PresentationTool::new`] so /// both tools register with an identical call). - pub fn new(workspace_dir: PathBuf, security: Arc) -> Self { + pub fn new( + workspace_dir: PathBuf, + files_dir: impl Into, + security: Arc, + ) -> Self { Self { workspace_dir, + files_dir: files_dir.into(), security, } } + + /// The agent-registry constructor: the artifact metadata goes to + /// `config.workspace_dir`, the document to the files folder (#5505). + pub fn for_config(config: &crate::config::Config, security: Arc) -> Self { + Self::new( + config.workspace_dir.clone(), + crate::agent::artifacts::FileRoots::from_config(config), + security, + ) + } } #[async_trait] @@ -201,6 +218,7 @@ impl Tool for DocumentTool { let (meta, output_path) = create_artifact( &self.workspace_dir, + &self.files_dir, ArtifactKind::Document, &input.title, "docx", @@ -227,7 +245,13 @@ impl Tool for DocumentTool { let bytes = match engine::generate(&input, GENERATION_TIMEOUT).await { Ok(bytes) => bytes, Err(err) => { - let _ = fail_artifact(&self.workspace_dir, &meta.id, &err.to_string()).await; + let _ = fail_artifact( + &self.workspace_dir, + &self.files_dir, + &meta.id, + &err.to_string(), + ) + .await; tracing::warn!( target: "document", err = %err, @@ -243,7 +267,7 @@ impl Tool for DocumentTool { .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_default(); let reason = format!("failed to write generated document ({filename}): {err}"); - let _ = fail_artifact(&self.workspace_dir, &meta.id, &reason).await; + let _ = fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &reason).await; tracing::warn!( target: "document", err = %err, @@ -264,7 +288,8 @@ impl Tool for DocumentTool { // stuck `Pending` spinner. Fail-artifact errors are // swallowed — they can only recur if the same ledger backend // is unavailable. - let _ = fail_artifact(&self.workspace_dir, &meta.id, &reason).await; + let _ = + fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &reason).await; tracing::warn!( target: "document", err = %err, diff --git a/crates/openhuman-core/src/tools/impl/presentation/mod.rs b/crates/openhuman-core/src/tools/impl/presentation/mod.rs index dd3f62f13ff..d9547675ae6 100644 --- a/crates/openhuman-core/src/tools/impl/presentation/mod.rs +++ b/crates/openhuman-core/src/tools/impl/presentation/mod.rs @@ -67,6 +67,8 @@ pub const TOOL_NAME: &str = "generate_presentation"; /// One-shot `.pptx` generator. See module docs for the request flow. pub struct PresentationTool { workspace_dir: PathBuf, + /// Visible folder the generated deck is written into (#5505). + files_dir: crate::agent::artifacts::FileRoots, /// Existing host config when the caller already owns the authoritative /// runtime snapshot. Keeping this optional preserves the ordinary agent /// constructor while avoiding a process-global config reload during @@ -84,22 +86,39 @@ impl PresentationTool { /// resolution, venv setup, or cache directory needed. Pass the /// workspace directory the artifact pipeline writes into, plus the /// active [`SecurityPolicy`] for validating `File`-source image paths. - pub fn new(workspace_dir: PathBuf, security: Arc) -> Self { + pub fn new( + workspace_dir: PathBuf, + files_dir: impl Into, + security: Arc, + ) -> Self { Self { workspace_dir, + files_dir: files_dir.into(), config: None, security, } } + /// The agent-registry constructor: the artifact metadata goes to + /// `config.workspace_dir`, the deck to the files folder (#5505). + pub fn for_config(config: &crate::config::Config, security: Arc) -> Self { + Self::new( + config.workspace_dir.clone(), + crate::agent::artifacts::FileRoots::from_config(config), + security, + ) + } + /// Construct the tool with an authoritative host config snapshot. pub(crate) fn with_config( workspace_dir: PathBuf, + files_dir: impl Into, security: Arc, config: crate::config::Config, ) -> Self { Self { workspace_dir, + files_dir: files_dir.into(), config: Some(config), security, } @@ -256,6 +275,7 @@ impl Tool for PresentationTool { let (meta, output_path) = create_artifact( &self.workspace_dir, + &self.files_dir, ArtifactKind::Presentation, &input.title, "pptx", @@ -289,7 +309,13 @@ impl Tool for PresentationTool { { Ok(bytes) => bytes, Err(err) => { - let _ = fail_artifact(&self.workspace_dir, &meta.id, &err.to_string()).await; + let _ = fail_artifact( + &self.workspace_dir, + &self.files_dir, + &meta.id, + &err.to_string(), + ) + .await; tracing::warn!( target: "presentation", err = %err, @@ -305,7 +331,7 @@ impl Tool for PresentationTool { .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_default(); let reason = format!("failed to write generated deck ({filename}): {err}"); - let _ = fail_artifact(&self.workspace_dir, &meta.id, &reason).await; + let _ = fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &reason).await; tracing::warn!( target: "presentation", err = %err, @@ -327,7 +353,8 @@ impl Tool for PresentationTool { // errors are swallowed — they can only happen if the same // ledger backend is unavailable, in which case nothing we // do here will help. - let _ = fail_artifact(&self.workspace_dir, &meta.id, &reason).await; + let _ = + fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &reason).await; tracing::warn!( target: "presentation", err = %err, @@ -412,7 +439,7 @@ impl PresentationTool { async fn resolve_one_image(&self, image: &SlideImage) -> Result { let bytes = match &image.source { SlideImageSource::Artifact { artifact_id } => { - read_artifact_bytes(&self.workspace_dir, artifact_id) + read_artifact_bytes(&self.workspace_dir, &self.files_dir, artifact_id) .await .map_err(|e| format!("artifact {artifact_id} unreadable: {e}"))? } diff --git a/crates/openhuman-core/src/tools/impl/presentation/presentation_tests.rs b/crates/openhuman-core/src/tools/impl/presentation/presentation_tests.rs index cfad6291d03..2722ba2fced 100644 --- a/crates/openhuman-core/src/tools/impl/presentation/presentation_tests.rs +++ b/crates/openhuman-core/src/tools/impl/presentation/presentation_tests.rs @@ -39,7 +39,11 @@ fn test_security(workspace: &Path) -> Arc { /// Build a tool whose security policy is rooted at `workspace`. fn make_tool(workspace: &Path) -> PresentationTool { - PresentationTool::new(workspace.to_path_buf(), test_security(workspace)) + PresentationTool::new( + workspace.to_path_buf(), + workspace.join("Files"), + test_security(workspace), + ) } fn minimal_input_json() -> serde_json::Value { diff --git a/crates/openhuman-core/src/tools/ops.rs b/crates/openhuman-core/src/tools/ops.rs index 81d9ce07c9a..48a5fae35cd 100644 --- a/crates/openhuman-core/src/tools/ops.rs +++ b/crates/openhuman-core/src/tools/ops.rs @@ -10,7 +10,7 @@ use std::sync::Arc; use tinyagents_harness::tools::{self as harness_tools, CurrentTimeTool, ResolveTimeTool}; use tinytools::Tool; #[cfg(test)] -use tinytools::{ToolResult, ToolSpec}; +use tinytools::ToolResult; use tinytools_std::detect_tools::DetectToolsTool; use tinytools_std::filesystem::{ ApplyPatchTool, CsvExportTool, EditFileTool, FileReadTool, FileWriteTool, GitOperationsTool, @@ -658,8 +658,8 @@ pub fn all_tools_with_runtime( // managed Python venv, no first-call install latency. Always // registered. #[cfg(feature = "documents")] - tools.push(Box::new(PresentationTool::new( - root_config.workspace_dir.clone(), + tools.push(Box::new(PresentationTool::for_config( + root_config, security.clone(), ))); @@ -668,8 +668,8 @@ pub fn all_tools_with_runtime( // real `.docx` through the same byte-agnostic artifact pipeline as // the presentation tool. Always registered; same constructor shape. #[cfg(feature = "documents")] - tools.push(Box::new(DocumentTool::new( - root_config.workspace_dir.clone(), + tools.push(Box::new(DocumentTool::for_config( + root_config, security.clone(), ))); diff --git a/crates/openhuman-core/src/tools/ops_tests_default_registry_tests.rs b/crates/openhuman-core/src/tools/ops_tests_default_registry_tests.rs index a9146e799ba..c8a0a1a7b88 100644 --- a/crates/openhuman-core/src/tools/ops_tests_default_registry_tests.rs +++ b/crates/openhuman-core/src/tools/ops_tests_default_registry_tests.rs @@ -1,50 +1,5 @@ use super::*; #[test] -fn default_tools_has_three() { - let security = Arc::new(SecurityPolicy::default()); - let tools = default_tools(security); - assert_eq!(tools.len(), 3); -} -#[test] -fn all_tools_includes_spawn_subagent() { - // Regression guard: the `spawn_subagent` tool must be present - // in the default registry so parent agents can delegate to - // sub-agents at runtime. If this test fails, the dispatch path - // in `agent::subagent_host` becomes unreachable. - let tmp = TempDir::new().unwrap(); - let security = Arc::new(SecurityPolicy::default()); - // The embedding seam fails loudly when unwired. - let _mem_cfg = MemoryConfig { - backend: "markdown".into(), - ..MemoryConfig::default() - }; - - let browser = BrowserConfig { - enabled: false, - allowed_domains: vec![], - session_name: None, - ..BrowserConfig::default() - }; - let http = crate::config::HttpRequestConfig::default(); - let cfg = test_config(&tmp); - - let tools = all_tools( - Arc::new(Config::default()), - &security, - AuditLogger::disabled(), - &browser, - &http, - tmp.path(), - &HashMap::new(), - &cfg, - ); - let names: Vec<&str> = tools.iter().map(|t| t.name()).collect(); - assert!( - names.contains(&"spawn_subagent"), - "spawn_subagent must be registered in the default tool list; got: {names:?}" - ); -} -#[test] fn all_tools_registers_collapsed_memory_and_search_tools() { let tmp = TempDir::new().unwrap(); let security = Arc::new(SecurityPolicy::default()); @@ -122,74 +77,6 @@ fn whatsapp_data_tools_are_gone_in_every_build() { } } #[test] -fn all_tools_includes_spawn_async_subagent() { - let tmp = TempDir::new().unwrap(); - let security = Arc::new(SecurityPolicy::default()); - // The embedding seam fails loudly when unwired. - let _mem_cfg = MemoryConfig { - backend: "markdown".into(), - ..MemoryConfig::default() - }; - let browser = BrowserConfig { - enabled: false, - allowed_domains: vec![], - session_name: None, - ..BrowserConfig::default() - }; - let http = crate::config::HttpRequestConfig::default(); - let cfg = test_config(&tmp); - - let tools = all_tools( - Arc::new(Config::default()), - &security, - AuditLogger::disabled(), - &browser, - &http, - tmp.path(), - &HashMap::new(), - &cfg, - ); - let names: Vec<&str> = tools.iter().map(|t| t.name()).collect(); - assert!( - names.contains(&"spawn_async_subagent"), - "spawn_async_subagent must be registered for fire-and-forget background orchestration; got: {names:?}" - ); -} -#[test] -fn all_tools_includes_spawn_parallel_agents() { - let tmp = TempDir::new().unwrap(); - let security = Arc::new(SecurityPolicy::default()); - // The embedding seam fails loudly when unwired. - let _mem_cfg = MemoryConfig { - backend: "markdown".into(), - ..MemoryConfig::default() - }; - let browser = BrowserConfig { - enabled: false, - allowed_domains: vec![], - session_name: None, - ..BrowserConfig::default() - }; - let http = crate::config::HttpRequestConfig::default(); - let cfg = test_config(&tmp); - - let tools = all_tools( - Arc::new(Config::default()), - &security, - AuditLogger::disabled(), - &browser, - &http, - tmp.path(), - &HashMap::new(), - &cfg, - ); - let names: Vec<&str> = tools.iter().map(|t| t.name()).collect(); - assert!( - names.contains(&"spawn_parallel_agents"), - "spawn_parallel_agents must be registered for orchestrated fan-out; got: {names:?}" - ); -} -#[test] fn every_packed_tool_name_resolves_to_a_registered_tool() { // A pack advertises a menu. `render_pack_filtered` skips a name it cannot // resolve (tools.rs "a pack may name a tool this build compiled out"), so a @@ -298,42 +185,6 @@ fn every_packed_tool_name_resolves_to_a_registered_tool() { delegate name); these do not: {missing:?}" ); } -#[test] -fn all_tools_always_registers_curl() { - // Regression guard: `curl` is always registered (gated only by - // the shared `http_request.allowed_domains` allowlist at call - // time, like `http_request`). `Write` permission level keeps it - // off agents that aren't allowed to modify the workspace. - let tmp = TempDir::new().unwrap(); - let security = Arc::new(SecurityPolicy::default()); - // The embedding seam fails loudly when unwired. This - // test doesn't use that helper (it needs the `Arc` alongside - // its own config setup below), so it installs the seams directly. - let _mem_cfg = MemoryConfig { - backend: "markdown".into(), - ..MemoryConfig::default() - }; - - let browser = BrowserConfig::default(); - let http = crate::config::HttpRequestConfig::default(); - let cfg = test_config(&tmp); - - let tools = all_tools( - Arc::new(cfg.clone()), - &security, - AuditLogger::disabled(), - &browser, - &http, - tmp.path(), - &HashMap::new(), - &cfg, - ); - let names: Vec<&str> = tools.iter().map(|t| t.name()).collect(); - assert!( - names.contains(&"curl"), - "curl must always be registered; got: {names:?}" - ); -} // Compile-time `media` feature gate (#4804). The media-generation agent tools // (`media_generate_*`) are present only when the `media` feature is compiled @@ -564,36 +415,6 @@ fn all_tools_skips_gitbooks_when_disabled() { ); } -#[test] -fn all_tools_includes_current_time() { - let tmp = TempDir::new().unwrap(); - let security = Arc::new(SecurityPolicy::default()); - // The embedding seam fails loudly when unwired. - let _mem_cfg = MemoryConfig { - backend: "markdown".into(), - ..MemoryConfig::default() - }; - - let browser = BrowserConfig::default(); - let http = crate::config::HttpRequestConfig::default(); - let cfg = test_config(&tmp); - - let tools = all_tools( - Arc::new(Config::default()), - &security, - AuditLogger::disabled(), - &browser, - &http, - tmp.path(), - &HashMap::new(), - &cfg, - ); - let names: Vec<&str> = tools.iter().map(|t| t.name()).collect(); - assert!( - names.contains(&"current_time"), - "current_time must be registered in the default tool list; got: {names:?}" - ); -} #[test] fn all_tools_default_registry_contains_expected_baseline_surface() { let tmp = TempDir::new().unwrap(); @@ -733,3 +554,53 @@ fn all_tools_excludes_browser_when_disabled() { assert!(names.contains(&"pushover")); assert!(names.contains(&"proxy_config")); } + +/// #5505: the producers write into the folder chosen in Settings, not a +/// hard-coded default. Generation itself needs the tinydocs module, which a +/// unit test does not have, but the artifact is reserved in the files folder +/// before generation runs, so its record names the folder either way. +#[cfg(feature = "documents")] +#[tokio::test] +async fn document_tool_writes_into_the_configured_files_folder() { + let tmp = TempDir::new().unwrap(); + let security = Arc::new(SecurityPolicy::default()); + let browser = BrowserConfig { + enabled: false, + ..BrowserConfig::default() + }; + let http = crate::config::HttpRequestConfig::default(); + let mut cfg = test_config(&tmp); + let chosen = tmp.path().join("Chosen"); + cfg.files_dir_override = Some(chosen.clone()); + let tools = all_tools( + Arc::new(Config::default()), + &security, + AuditLogger::disabled(), + &browser, + &http, + tmp.path(), + &HashMap::new(), + &cfg, + ); + let tool = tools + .iter() + .find(|t| t.name() == "generate_document") + .expect("generate_document registered"); + + let _ = tool + .execute(serde_json::json!({ + "title": "Charter", + "sections": [{ "heading": "Overview", "paragraphs": ["In brief."] }] + })) + .await; + + let (artifacts, _) = + crate::agent::artifacts::store::list_artifacts(&cfg.workspace_dir, 0, 10, None) + .await + .expect("list artifacts"); + assert_eq!(artifacts.len(), 1, "{artifacts:?}"); + assert_eq!( + artifacts[0].file_root.as_deref(), + Some(chosen.to_string_lossy().as_ref()) + ); +} diff --git a/crates/openhuman-core/src/tools/ops_tests_execution_and_serde_tests.rs b/crates/openhuman-core/src/tools/ops_tests_execution_and_serde_tests.rs index 7b116e71ac5..c926340abf6 100644 --- a/crates/openhuman-core/src/tools/ops_tests_execution_and_serde_tests.rs +++ b/crates/openhuman-core/src/tools/ops_tests_execution_and_serde_tests.rs @@ -67,16 +67,6 @@ fn all_tools_includes_browser_when_enabled() { assert!(names.contains(&"proxy_config")); } -#[test] -fn default_tools_names() { - let security = Arc::new(SecurityPolicy::default()); - let tools = default_tools(security); - let names: Vec<&str> = tools.iter().map(|t| t.name()).collect(); - assert!(names.contains(&"shell")); - assert!(names.contains(&"file_read")); - assert!(names.contains(&"file_write")); -} - #[test] fn default_tools_all_have_descriptions() { let security = Arc::new(SecurityPolicy::default()); @@ -109,49 +99,6 @@ fn default_tools_all_have_schemas() { } } -#[test] -fn tool_spec_generation() { - let security = Arc::new(SecurityPolicy::default()); - let tools = default_tools(security); - for tool in &tools { - let spec = tool.spec(); - assert_eq!(spec.name, tool.name()); - assert_eq!(spec.description, tool.description()); - assert!(spec.parameters.is_object()); - } -} - -#[test] -fn tool_result_serde() { - let result = ToolResult::success("hello"); - let json = serde_json::to_string(&result).unwrap(); - let parsed: ToolResult = serde_json::from_str(&json).unwrap(); - assert!(!parsed.is_error); - assert_eq!(parsed.output(), "hello"); -} - -#[test] -fn tool_result_with_error_serde() { - let result = ToolResult::error("boom"); - let json = serde_json::to_string(&result).unwrap(); - let parsed: ToolResult = serde_json::from_str(&json).unwrap(); - assert!(parsed.is_error); - assert_eq!(parsed.output(), "boom"); -} - -#[test] -fn tool_spec_serde() { - let spec = ToolSpec { - name: "test".into(), - description: "A test tool".into(), - parameters: serde_json::json!({"type": "object"}), - }; - let json = serde_json::to_string(&spec).unwrap(); - let parsed: ToolSpec = serde_json::from_str(&json).unwrap(); - assert_eq!(parsed.name, "test"); - assert_eq!(parsed.description, "A test tool"); -} - #[test] fn all_tools_includes_delegate_when_agents_configured() { let tmp = TempDir::new().unwrap(); diff --git a/crates/openhuman-core/src/tools/registry/providers_tests.rs b/crates/openhuman-core/src/tools/registry/providers_tests.rs index 8b6e6390dd4..51650821814 100644 --- a/crates/openhuman-core/src/tools/registry/providers_tests.rs +++ b/crates/openhuman-core/src/tools/registry/providers_tests.rs @@ -1,6 +1,9 @@ use crate::config::schema::{CapabilityProviderConfig, CapabilityProviderTrustState, Config}; -use super::CapabilityProviderRegistry; +use super::{ + capability_provider_by_id, is_capability_provider_trusted_enabled, list_capability_providers, + normalize_capability_provider_id, CapabilityProviderRegistry, +}; fn config_with(providers: Vec) -> Config { Config { @@ -111,3 +114,40 @@ fn invalid_provider_ids_are_rejected() { assert!(err.to_string().contains("invalid provider id")); } + +#[test] +fn blank_display_name_falls_back_to_normalized_id_and_lookups_normalize() { + let config = config_with(vec![CapabilityProviderConfig { + id: " Team Tools ".to_string(), + display_name: " ".to_string(), + source_uri: None, + source_digest: None, + trust_state: CapabilityProviderTrustState::Trusted, + enabled: true, + }]); + + assert_eq!( + normalize_capability_provider_id(" Team Tools "), + Ok("team-tools".to_string()) + ); + assert!(normalize_capability_provider_id("!!!").is_err()); + assert!(normalize_capability_provider_id(&"x".repeat(120)).is_err()); + + let registry = CapabilityProviderRegistry::from_config(&config).expect("valid provider"); + assert_eq!(registry.list()[0].display_name, "team-tools"); + assert!(registry.get("TEAM TOOLS").is_some()); + assert!(registry.get("!!!").is_none()); + + assert_eq!(list_capability_providers(&config).unwrap().len(), 1); + assert_eq!( + capability_provider_by_id(&config, "team tools") + .unwrap() + .expect("team provider") + .id, + "team-tools" + ); + assert!(is_capability_provider_trusted_enabled( + &config, + "team tools" + )); +} diff --git a/crates/openhuman-core/src/tools/schemas_tests.rs b/crates/openhuman-core/src/tools/schemas_tests.rs index d7089db0c3c..5663db08e39 100644 --- a/crates/openhuman-core/src/tools/schemas_tests.rs +++ b/crates/openhuman-core/src/tools/schemas_tests.rs @@ -78,9 +78,3 @@ fn web_search_schema_shape() { // callers can attribute a managed search (#5136). assert!(s.outputs.iter().any(|f| f.name == "provider")); } - -#[test] -fn unknown_function_returns_unknown() { - let s = tools_schemas("nonexistent"); - assert_eq!(s.function, "unknown"); -} diff --git a/crates/openhuman-core/src/tools/timeout/README.md b/crates/openhuman-core/src/tools/timeout/README.md index 64696b01b01..e4fc3b3808c 100644 --- a/crates/openhuman-core/src/tools/timeout/README.md +++ b/crates/openhuman-core/src/tools/timeout/README.md @@ -57,7 +57,6 @@ The global timeout governs non-scripting tools only, since a hung network or MCP - `crates/openhuman-core/src/agent/tools/delegate.rs`: bounds the delegated provider chat call with `tool_execution_timeout_secs`. - `crates/openhuman-core/src/config/ops/agent.rs`: `apply_agent_settings` calls `set_tool_timeout_secs` after persisting; `get_agent_settings` reports `effective_timeout_secs`/`env_override`. - `crates/openhuman-core/src/core/runtime/subscribers.rs`: `register_domain_subscribers` seeds the runtime value from config on the always-on core boot path, so channel-less or web-chat-only cores get the configured timeout too (#5027). -- `crates/openhuman-core/src/agent/harness/harness_gap_tests.rs`: pins `parse_tool_timeout_secs` default and boundary behavior. ## Notes and gotchas diff --git a/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests.rs b/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests.rs index f2b24343c0a..f327c8248cb 100644 --- a/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests.rs +++ b/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests.rs @@ -146,45 +146,6 @@ async fn a_packed_delegate_in_the_synthesised_set_is_reachable() { assert!(format!("{:?}", ran.content).contains("marker")); } -/// Replacing the synthesised `Arc` must re-point the handle at the new one. -/// -/// `refresh_delegation_tools` rebuilds that set on every Composio reconcile. A -/// handle left holding the old `Weak` stops upgrading once the last reader of -/// the previous allocation goes, and every packed delegate silently becomes -/// unreachable for the rest of the session — the same class of bug the durable -/// `OnceLock` rebinding fix already addressed on the other registry. -#[tokio::test] -async fn rebinding_the_synthesised_set_repoints_the_handle() { - let (durable, first) = split_registries("manage_profile_memory", PermissionLevel::ReadOnly); - let use_skill = find(&durable, USE_SKILL); - - // A reconcile: a fresh set, and the old allocation dropped. - let second: Arc>> = Arc::new(vec![Box::new(FakeTool { - name: "save_preference", - level: PermissionLevel::ReadOnly, - external: false, - timeout: ToolTimeout::Inherit, - })]); - bind_synthesized_pack_registry(&durable, &second); - drop(first); - - let ran = use_skill - .execute(json!({"skill": "profile", "tool": "save_preference", "args": {}})) - .await - .unwrap(); - assert!( - !ran.is_error, - "handle did not follow the rebind: {}", - ran.text() - ); - // And the retired instance is gone with its allocation. - let stale = use_skill - .execute(json!({"skill": "profile", "tool": "manage_profile_memory", "args": {}})) - .await - .unwrap(); - assert!(stale.is_error, "a dropped delegate stayed reachable"); -} - /// Closing a goal must stay directly callable. /// /// `goal_complete` is the one goal operation an agent reaches for reactively — @@ -249,49 +210,6 @@ fn an_empty_visible_set_is_left_alone() { assert!(visible.is_empty()); } -#[tokio::test] -async fn use_skill_without_a_tool_renders_the_schema_of_a_present_tool() { - let name = pack("web3").unwrap().tools[0]; - let tools = registry_with(name, PermissionLevel::ReadOnly); - let result = find(&tools, USE_SKILL) - .execute(json!({"skill": "web3"})) - .await - .unwrap(); - assert!(!result.is_error); - let text = format!("{:?}", result.content); - assert!(text.contains(name), "rendered pack omitted `{name}`"); - assert!( - text.contains("marker"), - "rendered pack omitted the arg schema" - ); -} - -#[tokio::test] -async fn use_skill_refuses_a_tool_from_another_skill() { - // Cross-skill dispatch would make the `skill` argument decoration and let a - // workflow skill reach a crypto write. - let crypto = pack("web3").unwrap().tools[0]; - let tools = registry_with(crypto, PermissionLevel::Dangerous); - let result = find(&tools, USE_SKILL) - .execute(json!({"skill": "workflows", "tool": crypto, "args": {}})) - .await - .unwrap(); - assert!(result.is_error, "cross-skill dispatch was admitted"); -} - -#[test] -fn use_skill_reports_the_inner_tools_permission_level() { - // The harness gates on this. Reporting the proxy's own level would launder - // a dangerous packed tool onto a channel that refuses it. - let name = pack("web3").unwrap().tools[0]; - let tools = registry_with(name, PermissionLevel::Dangerous); - let use_skill = find(&tools, USE_SKILL); - assert_eq!( - use_skill.permission_level_with_args(&json!({"skill": "web3", "tool": name})), - PermissionLevel::Dangerous - ); -} - #[test] fn every_pack_declares_the_tools_it_is_named_for() { // Membership is compiled-in data, so a typo here is invisible until a diff --git a/crates/openhuman-core/src/voice/compile_status_tests.rs b/crates/openhuman-core/src/voice/compile_status_tests.rs index 72962ee6479..c010f2c77dc 100644 --- a/crates/openhuman-core/src/voice/compile_status_tests.rs +++ b/crates/openhuman-core/src/voice/compile_status_tests.rs @@ -7,19 +7,3 @@ use super::VOICE_COMPILED_IN; fn reports_the_compiled_gate_state() { assert_eq!(VOICE_COMPILED_IN, cfg!(feature = "voice")); } - -/// The default build ships voice; this is the state the desktop app -/// requires (#4901). Skipped when the slim build is under test. -#[test] -#[cfg(feature = "voice")] -fn is_true_when_the_voice_feature_is_on() { - assert!(VOICE_COMPILED_IN); -} - -/// The slim build must report honestly, otherwise the shell's const assert -/// would pass against a stubbed core and #4901 could ship again. -#[test] -#[cfg(not(feature = "voice"))] -fn is_false_when_the_voice_feature_is_off() { - assert!(!VOICE_COMPILED_IN); -} diff --git a/crates/openhuman-core/src/voice/schemas_tests.rs b/crates/openhuman-core/src/voice/schemas_tests.rs index 390920368a1..95dd5d910bf 100644 --- a/crates/openhuman-core/src/voice/schemas_tests.rs +++ b/crates/openhuman-core/src/voice/schemas_tests.rs @@ -109,12 +109,6 @@ fn tts_schema_has_optional_output_path() { assert!(!output_path.required); } -#[test] -fn unknown_schema_returns_fallback() { - let s = voice_schemas("voice_nonexistent"); - assert_eq!(s.function, "unknown"); -} - #[test] fn deserialize_params_applies_defaults() { let params = Map::from_iter([ diff --git a/crates/openhuman-core/src/voice/types_tests.rs b/crates/openhuman-core/src/voice/types_tests.rs index 7b3efa0fb4c..17bf2dfec81 100644 --- a/crates/openhuman-core/src/voice/types_tests.rs +++ b/crates/openhuman-core/src/voice/types_tests.rs @@ -70,17 +70,3 @@ fn from_local_ai_tts_result() { assert_eq!(voice.output_path, "/out.wav"); assert_eq!(voice.voice_id, "voice1"); } - -#[test] -fn serde_round_trip_speech_result() { - let original = VoiceSpeechResult { - text: "round trip".into(), - raw_text: "round trip uh".into(), - model_id: "model".into(), - }; - let json = serde_json::to_string(&original).unwrap(); - let decoded: VoiceSpeechResult = serde_json::from_str(&json).unwrap(); - assert_eq!(decoded.text, original.text); - assert_eq!(decoded.raw_text, original.raw_text); - assert_eq!(decoded.model_id, original.model_id); -} diff --git a/crates/openhuman-core/src/web3/wallet/schemas_tests.rs b/crates/openhuman-core/src/web3/wallet/schemas_tests.rs index 7a17c688ac5..fa29dd51176 100644 --- a/crates/openhuman-core/src/web3/wallet/schemas_tests.rs +++ b/crates/openhuman-core/src/web3/wallet/schemas_tests.rs @@ -67,9 +67,3 @@ fn prepare_transfer_schema_marks_asset_symbol_optional() { .expect("assetSymbol input present"); assert!(!asset.required); } - -#[test] -fn unknown_schema_maps_to_unknown() { - let schema = wallet_schemas("wat"); - assert_eq!(schema.function, "unknown"); -} diff --git a/crates/openhuman-core/src/web3/wallet/test_support.rs b/crates/openhuman-core/src/web3/wallet/test_support.rs index 9b67ae1b25d..b71a628b675 100644 --- a/crates/openhuman-core/src/web3/wallet/test_support.rs +++ b/crates/openhuman-core/src/web3/wallet/test_support.rs @@ -178,7 +178,3 @@ pub(crate) async fn setup_wallet_in(temp: &TempDir) -> Result std::env::set_var("OPENHUMAN_WORKSPACE", value), - None => std::env::remove_var("OPENHUMAN_WORKSPACE"), - } -} diff --git a/crates/openhuman-core/src/web_chat/web_tests.rs b/crates/openhuman-core/src/web_chat/web_tests.rs index 6ccc63d7006..cb92631fa9f 100644 --- a/crates/openhuman-core/src/web_chat/web_tests.rs +++ b/crates/openhuman-core/src/web_chat/web_tests.rs @@ -4,9 +4,9 @@ use super::{ channel_web_queue_status, classify_inference_error, drain_queued_turns_for_test, event_session_id_for, generic_inference_error_user_message, in_flight_entries_for_test, inference_budget_exceeded_user_message, - is_inference_budget_exceeded_error, json_output, key_for, locale_reply_directive, - normalize_model_override, optional_f64, optional_string, parallel_in_flight_entries_for_test, - provider_role_for_model_override, required_string, schemas, sentry_suppression_reason, + is_inference_budget_exceeded_error, key_for, locale_reply_directive, + normalize_model_override, parallel_in_flight_entries_for_test, + provider_role_for_model_override, schemas, sentry_suppression_reason, set_test_forced_run_chat_task_error, set_test_run_chat_task_block, start_chat, subscribe_web_channel_events, ChatRequestMetadata, ClassifiedError, StartChatError, TestRunChatTaskBlock, WebChatParams, diff --git a/crates/openhuman-core/src/web_chat/web_tests_error_code_classification_tests.rs b/crates/openhuman-core/src/web_chat/web_tests_error_code_classification_tests.rs index 04418747d50..f2a61707d50 100644 --- a/crates/openhuman-core/src/web_chat/web_tests_error_code_classification_tests.rs +++ b/crates/openhuman-core/src/web_chat/web_tests_error_code_classification_tests.rs @@ -535,42 +535,6 @@ fn normalize_model_override_trims_value() { ); } -// ── Broadcast events ────────────────────────────────────────── - -#[test] -fn subscribe_web_channel_events_returns_receiver() { - // Just confirm we can subscribe without panic. - let _rx = subscribe_web_channel_events(); -} - -// ── Field builder helpers ───────────────────────────────────── - -#[test] -fn required_string_marks_field_required() { - let f = required_string("client_id", "c"); - assert!(f.required); - assert!(matches!(f.ty, TypeSchema::String)); -} - -#[test] -fn optional_string_marks_field_optional() { - let f = optional_string("model", "c"); - assert!(!f.required); -} - -#[test] -fn optional_f64_marks_field_optional() { - let f = optional_f64("temperature", "c"); - assert!(!f.required); -} - -#[test] -fn json_output_is_required_json_field() { - let f = json_output("ack", "c"); - assert!(f.required); - assert!(matches!(f.ty, TypeSchema::Json)); -} - #[test] fn fingerprint_autonomy_change_is_cache_miss() { // Changing the agent-access policy must invalidate the cached agent so the @@ -599,16 +563,6 @@ fn fingerprint_model_registry_change_is_cache_miss() { ); } -#[test] -fn fingerprint_identical_inputs_are_cache_hit() { - let a = fp(None, None, "orchestrator", "anthropic:claude-sonnet-4-6"); - let b = fp(None, None, "orchestrator", "anthropic:claude-sonnet-4-6"); - assert_eq!( - a, b, - "identical fingerprints must compare equal (cache hit)" - ); -} - #[test] fn classify_inference_error_in_stream_tool_history_rejection_uses_malformed_history_copy() { // #6724: a provider failure delivered inside an HTTP 200 stream reaches diff --git a/docs/RELEASE-MANUAL-SMOKE.md b/docs/RELEASE-MANUAL-SMOKE.md index b3008c2205d..a8b05880e8b 100644 --- a/docs/RELEASE-MANUAL-SMOKE.md +++ b/docs/RELEASE-MANUAL-SMOKE.md @@ -90,6 +90,7 @@ Applies to every release, all platforms. ### Cross-platform +- [ ] **Agent files land in a visible folder** — Ask the agent for a short document or deck. Expected: the file appears in `~/OpenHuman/projects/Files` under its title (not in `~/.openhuman`); **Show in folder** in the chat Files panel opens the file manager at it; Settings → Agent OS access → **Files folder** shows that path, **Show in folder** opens it, and choosing another folder sends the next file there while the earlier file still opens. On an upgraded install, files from before the upgrade have moved into the folder. - [ ] **Caller-owned inference works without an OpenHuman session** — In a local workspace without an OpenHuman login, configure Ollama/LM Studio/MLX/oMLX/local-openai or an independently authenticated Claude Code/Agent SDK provider. Run chat and an agent flow routed entirely to that provider. For a named harness agent, also configure the summarization route to managed inference and verify that the agent still uses its local route; reversing those routes must retain the managed agent's session requirement. Expected: no OpenHuman session requirement. Select managed inference instead: it must still require a backend session. With LocalOnly privacy enabled, local runtimes remain allowed and Claude subprocesses remain blocked as external inference. - [ ] **LocalOnly blocks remote search** — Configure a remote search provider and enable LocalOnly privacy. Invoke `web_search_tool` with a harmless query. Expected: the tool returns a policy-blocked result and does not dispatch to the provider. Switch privacy to Standard and confirm the same tool can complete. diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md index 224f7710374..393fe2f751e 100644 --- a/docs/TEST-COVERAGE-MATRIX.md +++ b/docs/TEST-COVERAGE-MATRIX.md @@ -264,6 +264,7 @@ End-to-end coverage of the agent harness via the web-chat RPC surface against an | 6.1.1 | File Read Access | RU+WD | `vendor/tinyagents/vendor/tinytools/crates/tinytools-std/src/filesystem/file_read/mod.rs`, `app/test/e2e/specs/tool-filesystem-flow.spec.ts` | ✅ | Was 🟡 — WDIO drives memory_read_file + asserts via Node fs. Byte `offset` paging (continues a paged artifact read, #6284): `file_read/test.rs::file_read_offset_continues_from_the_given_byte` (tinytools-std) | | 6.1.2 | File Write Access | RU+WD | `vendor/tinyagents/vendor/tinytools/crates/tinytools-std/src/filesystem/file_write/mod.rs`, `app/test/e2e/specs/tool-filesystem-flow.spec.ts` | ✅ | Was 🟡 — WDIO drives memory_write_file + asserts bytes match on disk | | 6.1.3 | Path Restriction Enforcement | RU+WD | `crates/openhuman-core/src/tools/impl/filesystem/gate_tests.rs`, `app/test/e2e/specs/tool-filesystem-flow.spec.ts` | ✅ | Was 🟡 — WDIO asserts traversal + absolute-path denial envelope | +| 6.1.4 | Agent deliverables in the visible Files folder | RU+VU | `crates/openhuman-core/src/agent/artifacts/files_tests.rs`, `crates/openhuman-core/src/agent/artifacts/migrate_tests.rs`, `crates/openhuman-core/src/agent/artifacts/ops_tests.rs`, `crates/openhuman-app/src/artifact_commands_tests.rs`, `app/src/services/__tests__/artifactDownloadService.test.ts`, `crates/openhuman-core/src/config/ops_files_dir_tests.rs`, `app/src/components/settings/panels/__tests__/FilesFolderSection.test.tsx`, `app/src/components/chat/__tests__/ChatFilesPanel.test.tsx` | ✅ | Files land in `~/OpenHuman/projects/Files` with human names (`create_new`, ` (2)` on collision, shared across accounts without clobbering; per-account listing); escape guard on the recorded file; "file missing" for a file removed outside OpenHuman; crash-safe idempotent migration of legacy files; Download resolves an artifact id through the core; the folder is chosen in Settings → Agent OS access and validated (absolute, not protected, not inside the data folder); Show in folder on every ready file in the Files panel and on the settings row (#5505) | ### 6.2 Shell & Git @@ -357,7 +358,7 @@ End-to-end coverage of the agent harness via the web-chat RPC surface against an | 8.2.5 | Coding-session persona ingestion | RU+RI+VU+WD | `vendor/tinymemory/crates/tinymemory-core/src/engine/persona_tests.rs` (vendored `tinymemory`), `crates/openhuman-core/src/memory/sources/rpc_tests.rs`, `tests/json_rpc_e2e.rs`, `app/src/components/intelligence/__tests__/CodingSessionsCard.test.tsx`, `app/src/services/memorySourcesService.test.ts`, `app/test/e2e/specs/coding-session-memory.spec.ts`, `app/test/playwright/specs/coding-session-memory.spec.ts` | ✅ | Discovers Codex and Claude Code histories, excludes machine-authored turns, exposes status/ingest RPCs, and surfaces incremental ingestion on Brain > Sources | | 8.2.6 | Folder-source path picker | RU+VU | `crates/openhuman-app/src/directory_picker.rs`, `app/src/utils/tauriCommands/directoryPicker.test.ts`, `app/src/components/intelligence/FolderField.test.tsx` | ✅ | Browse resolves an absolute path through the OS-native chooser and refuses to store a non-resolvable value (bare directory name) when none is available (#5831) | | 8.2.7 | Sync History and live sync activity | RU+RI+VU | `crates/openhuman-core/src/memory/sources/run_history_tests.rs`, `crates/openhuman-core/src/memory/sources/rpc/driver_run_tests.rs`, `crates/openhuman-core/src/memory/sources/rpc_monthly_summary_tests_tests.rs`, `crates/openhuman-core/src/integrations/composio/ops/connector_runs_tests.rs`, `crates/openhuman-core/src/integrations/composio/ops/source_rows_tests.rs`, `crates/openhuman-core/src/memory/sync_activity_tests.rs`, `tests/memory_sources_e2e.rs` (`sources_sync_dispatches_to_the_module_rather_than_refusing_the_capability`), `app/src/components/intelligence/SyncAuditPanel.test.tsx`, `app/src/components/intelligence/SyncActivityCard.test.tsx`, `app/src/components/intelligence/__tests__/memorySyncActivityStore.test.ts`, `app/src/components/intelligence/MemorySourceRow.test.tsx`, `app/src/components/intelligence/MemoryTreeStatusPanel.test.tsx` | ✅ | Every host-driven run (Sync button, Apply all, Composio) leaves one history row merged with the driver's audit log; manual driver runs end in `completed` or `failed`; a late per-document stage cannot reopen a finished row; Brain > Sync shows what is syncing and the job queue, and re-reads the history when a run ends (#6257) | -| 8.2.8 | Selectable memory engines and migration | RU+RI+VU | `crates/openhuman-core/src/memory/ops/engine_migrate_tests.rs`, `crates/openhuman-core/src/memory/ops/engine_tests.rs`, `tests/memory_engine_e2e.rs`, `tests/memory_engine_migrate_e2e.rs`, `tests/memory_hosted_surface_e2e.rs`, `app/src/components/settings/panels/MemoryEnginePanel.test.tsx`, `app/src/components/settings/panels/MemoryEngineErrorAlert.test.tsx`, `app/src/components/intelligence/MemoryFamilyGate.test.tsx`, `app/src/pages/__tests__/Brain.test.tsx` | ✅ | Engine selection, migration copy/cancel/failure behavior, hosted and external drivers, and capability gating; on the hosted engine a 403 reads `MEMORY_FORBIDDEN:` (never a sign-out), an outage `MEMORY_UNREACHABLE:`, and Brain's sync panels say "Not available" (#6718) | +| 8.2.8 | Selectable memory engines and migration | RU+RI+VU | `crates/openhuman-core/src/memory/ops/engine_migrate_tests.rs`, `crates/openhuman-core/src/memory/ops/engine_tests.rs`, `tests/memory_engine_e2e.rs`, `tests/memory_engine_migrate_e2e.rs`, `tests/memory_hosted_surface_e2e.rs`, `app/src/components/settings/panels/MemoryEnginePanel.test.tsx`, `app/src/components/settings/panels/MemoryEngineErrorAlert.test.tsx`, `app/src/components/intelligence/MemoryFamilyGate.test.tsx`, `app/src/pages/__tests__/Brain.test.tsx` | ✅ | Engine selection, migration copy/cancel/failure behavior, hosted and external drivers, and capability gating; on the hosted engine a 403 reads `MEMORY_FORBIDDEN:` (never a sign-out), an outage `MEMORY_UNREACHABLE:`, and Brain's sync panels say "Not available" (#6718). The hosted engine serves goals, tool rules, documents, the source sink and maintenance (`memory_hosted_surface_e2e.rs::the_hosted_engine_serves_documents_and_tool_rules`), draws the Brain graph from the server's derived facts (`::the_hosted_engine_draws_the_brain_graph_from_its_understanding`), and takes a local folder synced by the host (`::a_local_folder_syncs_into_hosted_memory`, `memory/sources/hosted_sync_tests.rs`); Brain gates coding sessions on their own family and local-store controls on `chunks` | ### 8.3 Memory Retrieval Benchmarks diff --git a/gitbooks/developing/engines.md b/gitbooks/developing/engines.md index 19637072505..747bf4ef6e0 100644 --- a/gitbooks/developing/engines.md +++ b/gitbooks/developing/engines.md @@ -120,19 +120,43 @@ the engine refuses, such as an API key without the memory scope) reads `MEMORY_FORBIDDEN:` and never signs the user out, and a timeout, refused connection, 429 or 5xx that outlasts the retries reads `MEMORY_UNREACHABLE:`. -Not every engine advertises every capability family. The hosted and CortexDB -engines have no `documents`, `tree`, `sources` or `graph` families, so the -document, tree and source RPCs answer a clean "does not support" error on them -(see the [`memory/driver` README](../../crates/openhuman-core/src/memory/driver/README.md) -for the full table). Brain's sync panels (activity, history, coding sessions) -need `sources` and show "Not available" there. - -Auto-recall reads the notes a user saved through the mandatory recall on such an -engine. Hosted CortexDB ranks its recall without scoring it, so its notes cannot -be floored on similarity: the lane keeps the engine's first three, behind the -same gate that decides whether a message needs memory at all. Situational -preferences and the contradiction check need a scored engine and stay empty -there. A lookup the engine refuses (out of credits, session not accepted, +Not every engine advertises every capability family, and the RPCs of a family +an engine lacks answer a clean "does not support" error (see the +[`memory/driver` README](../../crates/openhuman-core/src/memory/driver/README.md) +for the full table). + +- **Hosted engine.** It serves `goals`, `tool_memory`, `documents`, `sources` + (the sink connector sync writes to), `maintenance` (a health report), + `retrieval`, `ingest`, `profile`, `episodic`, `scoring` and `tree`. + Connector sync, goals, tool rules, documents, episodic memory and the learned + profile work there, the memory doctor reports the hosted service's health, + and the Brain graph draws the facts, beliefs and concepts the server derived + from what was written. +- **Direct CortexDB engine.** It serves none of those. +- **Neither.** No remote engine serves `graph`, `chunks`, `entities`, + `source_sync` or `coding_sessions`. + +Brain's sync panels (activity and history) need `sources`, its coding-sessions +card needs `coding_sessions`, and the controls and status that work on a local +chunk store (reset, rebuild, vault, pipeline status) need `chunks`. Each shows +"Not available", or is left out, on an engine without its family. Hosted memory +runs no source pipeline of its own, so the host syncs local folder, GitHub, RSS +and web-page sources itself: it reads them and sends the items through the +engine's sink, from the Sync button, Apply all, and a daily schedule +(`memory/sources/hosted_sync.rs`, `hosted_periodic.rs`). The host records what +the sink accepted, so a run sends only new or changed items and one stopped by +its budget carries on where it stopped. A file removed from a synced folder +stays in memory, and removing the source keeps what it synced, as on the local +engine; deleting the source's memory forgets all of it. + +Hosted CortexDB ranks its recall without scoring it: a hit carries its rank and +no signal (no similarity, keyword, graph, episodic or freshness), with or +without the retrieval family. Auto-recall keeps such notes in the engine's +order, its first three, behind the same gate that decides whether a message +needs memory at all, and hybrid search keeps the engine's order. Situational +preferences and the contradiction check need a measured similarity and stay +empty there. Summaries need a model the hosted engine does not reach, so a +segment's recap is the heuristic one. A lookup the engine refuses (out of credits, session not accepted, credential refused, unreachable) puts a one-line reason in the recall block instead of an empty result, so the model says memory is unavailable rather than that something was never stored. diff --git a/gitbooks/guides/move-to-new-pc.md b/gitbooks/guides/move-to-new-pc.md index 84ef80c21f3..3576968a952 100644 --- a/gitbooks/guides/move-to-new-pc.md +++ b/gitbooks/guides/move-to-new-pc.md @@ -62,7 +62,7 @@ Copy the **entire** data folder from the old machine to the same location on the Copy the whole folder rather than cherry-picking. It keeps memory, persona, config, and history consistent with each other. -The data folder holds config and memory but **not** the files the agent created or edited in its action sandbox. Also copy your **projects/action folder**, by default `~/OpenHuman/projects` (or wherever you pointed the action directory). Otherwise those project files stay behind on the old PC. +The data folder holds config and memory but **not** the files the agent created or edited in its action sandbox. Also copy your **projects/action folder**, by default `~/OpenHuman/projects` (or wherever you pointed the action directory). Otherwise those project files stay behind on the old PC. That folder also holds `Files` (`~/OpenHuman/projects/Files`), where the decks, documents and generated images and videos the agent delivers are saved. {% hint style="warning" %} Copy it somewhere secure. This folder contains your personal memory in readable form. Treat the transfer like moving personal documents. diff --git a/scripts/ci/check-gated-test-allowlist.sh b/scripts/ci/check-gated-test-allowlist.sh index 054675caf85..9c8d9da9593 100755 --- a/scripts/ci/check-gated-test-allowlist.sh +++ b/scripts/ci/check-gated-test-allowlist.sh @@ -51,7 +51,6 @@ tools/ops_tests_default_registry_tests.rs tools/ops_tests_domain_family_tests.rs tools/registry/ops_tests.rs tools/registry/schemas_tests.rs -voice/compile_status_tests.rs web3/stub.rs web3/wallet/stub.rs web3/x402/stub.rs diff --git a/scripts/ci/ignored-test-baseline.json b/scripts/ci/ignored-test-baseline.json index 4ccd671fcf4..49e2ee4016f 100644 --- a/scripts/ci/ignored-test-baseline.json +++ b/scripts/ci/ignored-test-baseline.json @@ -1,7 +1,7 @@ { "openhuman-app": 5, "openhuman-cli": 0, - "openhuman-core": 68, + "openhuman-core": 45, "openhuman-embed": 0, "openhuman-rpc": 1, "openhuman-tinyhumans": 0, diff --git a/scripts/ci/module-pin-exemptions.json b/scripts/ci/module-pin-exemptions.json index da832b35e8d..f325df2b427 100644 --- a/scripts/ci/module-pin-exemptions.json +++ b/scripts/ci/module-pin-exemptions.json @@ -36,12 +36,6 @@ "expect": "v0.2.7-6-g1be38d24", "reason": "The provider is published independently at v0.2.3 while the shared source pin is tinyruntime v0.2.7. v0.2.3 was built against tinyruntime 09f9646 (v0.2.4-5); git diff 09f9646..v0.2.7 changes no crate source (only CI, toolchain, versions, Cargo.lock and the tinybus pin), and the tinybus module ABI is revision 1 on both. Registry retains its matching published v0.2.3 provider artifact. The shared source pin additionally carries tinyruntime-pyserver: The pin is v0.2.7 plus only the new pure-library crate tinyruntime-pyserver (tinyhumansai/tinyruntime#19, branch oh-pyserver-on-v0.2.7), which the core links as a Rust path dependency for runtime::python_server. No module, contract or bus source changes relative to v0.2.7, so the registry's artifact still matches the contract compiled here. Remove when tinyruntime#19 ships in a release and both pins move to it." }, - { - "id": "tinymemory", - "submodule": "vendor/tinymemory", - "expect": "v1.18.0-52-g0f5af00c", - "reason": "The pin is tinymemory main (v1.18.0 plus tinymemory#170 conversations and #172 scheduler_gate_decide) plus pure-library additions only: the new crate tinymemory-guard (GuardedProvider) and conformance seeds (FixedRecallProvider, InMemoryProvider::len, RecordingProvider::with_session_turns/with_pending_segments), tinymemory#173 (branch w4-memory-guard); then tinymemory#174 (branch w4-memory-rest, stacked on #173): the new crates tinymemory-safety, tinymemory-tools, tinymemory-gate and tinymemory-import, the composio/twitter readers, reader_for_request and the pure reconcile decisions in tinymemory-sources, and tinymemory-core re-exporting those readers instead of carrying adapters (its nested tinycortex is bumped to tinycortex#178, which delegates store::safety to tinymemory-safety). The core links them as Rust path dependencies. No module, contract or bus source changes, so the registry's v1.17.0 artifact still matches the contract compiled here. Remove when #170, #172, #173 and #174 ship in a release and both pins move to it." - }, { "id": "tinybox", "submodule": "vendor/tinybox", diff --git a/tests/README.md b/tests/README.md index 69b325fbdbd..a50e7c49d44 100644 --- a/tests/README.md +++ b/tests/README.md @@ -10,7 +10,7 @@ the crate — but every file here compiles against and links `openhuman_core::` | Path | Purpose | | --- | --- | | `*.rs` | Integration/E2E targets, one Cargo `[[test]]` per file. `json_rpc_e2e.rs` is the canonical home for JSON-RPC behavior (see `AGENTS.md`). | -| `raw_coverage/*.rs` | Coverage suites (~90 files, mostly `*_raw_coverage_e2e.rs` plus some `*_e2e.rs`) compiled as modules of a single `raw_coverage_all` target instead of standalone binaries. `raw_coverage/w4_shared/mod.rs` is a shared harness three of them pull in with `#[path]`, not a suite. | +| `raw_coverage/*.rs` | Coverage suites (~30 files, mostly `*_raw_coverage_e2e.rs` plus some `*_e2e.rs`) compiled as modules of a single `raw_coverage_all` target instead of standalone binaries. `raw_coverage/w4_shared/mod.rs` is a shared harness three of them pull in with `#[path]`, not a suite. | | `raw_coverage_all.rs` | Aggregator: includes every top-level `raw_coverage/*.rs` file as a module. The module list is generated by root `build.rs` into `$OUT_DIR/raw_coverage_mods.rs`, so a new `raw_coverage/` file is picked up automatically with no manual registration. A file's own `#![cfg(...)]` gate still applies to just that module, and suites that mutate process-global env serialize on `SHARED_ENV_LOCK`, since they now share one process instead of one per file (see the file's own doc comment for the full rationale). | | `support/` | Helpers pulled into targets with `#[path]` (e.g. `noop_memory.rs`) because integration targets can't see `pub(crate)` items from the crate under test. | | `fixtures/` | Test data: `composio_*.json` tool fixtures, `memory/`, `memory_golden/` (generated — see its own README, regenerate with `scripts/regen-memory-golden-fixture.sh`), `polymarket/`. | diff --git a/tests/memory_engine_e2e.rs b/tests/memory_engine_e2e.rs index 7bf58b28d00..26555e90789 100644 --- a/tests/memory_engine_e2e.rs +++ b/tests/memory_engine_e2e.rs @@ -226,21 +226,26 @@ fn engine_set_binds_the_hosted_engine_without_a_restart_and_switches_back() { "graph must be gated with the stable error: {message}" ); - // An unsupported family degrades to a clean error, not a panic. + // The hosted engine serves documents (tinymemory's hosted-families + // spec): a titled document round-trips beside the stored note. let doc = fx .call( "openhuman.memory_doc_put", json!({ - "namespace": NS, "key": "k", "title": "t", "content": "c", + "namespace": NS, "key": "k", "title": "A title", "content": "c", "source_type": "doc", "priority": "medium", "tags": [], "metadata": null, "category": "core" }), ) .await; + result_of(&doc, "doc_put on the hosted engine"); + let v = fx + .call("openhuman.memory_doc_list", json!({ "namespace": NS })) + .await; + let docs = result_of(&v, "doc_list after doc_put on hosted"); assert!( - error_message(&doc, "doc_put on the hosted engine") - .contains("memory driver does not support the documents family"), - "doc_put must name the missing family: {doc}" + docs.to_string().contains("A title") && docs.to_string().contains("engine-note"), + "doc_list must list the titled document and the stored note: {docs}" ); // And back to the module, live. diff --git a/tests/memory_hosted_surface_e2e.rs b/tests/memory_hosted_surface_e2e.rs index 978aadab0f6..e82cefedc17 100644 --- a/tests/memory_hosted_surface_e2e.rs +++ b/tests/memory_hosted_surface_e2e.rs @@ -4,10 +4,15 @@ //! The four memory suites (`memory_roundtrip_e2e`, `memory_sources_e2e`, //! `memory_graph_roundtrip_e2e`, `memory_tree_health_e2e`) run on the local //! module, whose engine serves every family. The hosted engine serves the -//! mandatory families plus ingestion and answers; this suite holds it to what -//! that means for a user: what it serves works, what it does not serve answers -//! a clean refusal rather than failing some other way, auto-recall reaches the -//! notes a user saved, and a refused lookup says why. +//! mandatory families, ingestion and answers, and goals, tool rules, documents, +//! the source sink, maintenance, retrieval, ingest, profile, episodic memory, +//! scoring and a tree drawn from the server's understanding (tinymemory's +//! hosted-families spec); local sources are synced by the host through its +//! sink. This suite holds it to what that means for a user: what it serves +//! works, what it does not serve answers a clean refusal rather than failing +//! some other way, auto-recall reaches the notes a user saved, a refused lookup +//! says why, the Brain graph draws what the server understood, and a synced +//! folder reaches hosted memory. //! //! ```text //! RUST_MIN_STACK=67108864 cargo test -p openhuman-cli \ @@ -119,12 +124,10 @@ fn a_refused_credential_and_an_outage_have_their_own_names() { }); } -/// The handler answers from the host log when the driver keeps no run log -/// (`SourceSync` is absent), for a driver that serves the `Sources` sink -/// without owning pipelines. This fixture builds no `CoreContext`, so the -/// registry's capability gate stays open and the handler is reachable here. -/// In the app, an engine without `Sources` (hosted among them) has no -/// `memory_sources.*` methods at all, and Brain gates the panel on that. +/// The handler answers from the host log when the driver keeps no run log: +/// hosted memory serves the `Sources` sink without owning pipelines +/// (`SourceSync` is absent), so its `memory_sources.*` methods are registered +/// and Sync History reads what the host recorded. #[test] fn sync_history_answers_from_the_host_log_on_an_engine_without_one() { run_on_big_stack("hosted-sync-history", || async { @@ -139,6 +142,172 @@ fn sync_history_answers_from_the_host_log_on_an_engine_without_one() { }); } +/// The Brain graph on hosted memory is the server's understanding: a fact it +/// derived from the user's notes is a node labelled by what it says, under +/// the namespace it came from, named for what that holds. +#[test] +fn the_hosted_engine_draws_the_brain_graph_from_its_understanding() { + run_on_big_stack("hosted-graph", || async { + let fx = Fixture::new().await; + bind_hosted(&fx).await; + fx.hosted.layers.lock().unwrap().insert( + ("facts".to_string(), "tm:global".to_string()), + vec![json!({ + "id": "fact_tea", + "scope": "tm:global", + "subject": { "type": "entity", "id": "ent_user", "name": "User" }, + "predicate": "prefers", + "object": { "type": "literal", "datatype": "string", "value": "oolong tea" }, + "supports": [], + "confidence": 0.9, + "valid_from": "2026-09-01T00:00:00Z", + "recorded_from": "2026-09-01T00:00:00Z", + })], + ); + let v = fx + .call( + "openhuman.memory_tree_graph_export", + json!({ "mode": "tree" }), + ) + .await; + let graph = result_of(&v, "graph export on hosted"); + let labels: Vec<&str> = graph["nodes"] + .as_array() + .expect("nodes") + .iter() + .filter_map(|node| node["label"].as_str()) + .collect(); + assert!(labels.contains(&"User prefers oolong tea"), "{graph}"); + assert!( + labels.contains(&"Memory"), + "the global namespace reads as what it holds: {graph}" + ); + unbind(&fx).await; + }); +} + +/// A folder source on hosted memory is read by the host and sent through the +/// engine's sink, and the run lands in Sync History like any other. +#[test] +fn a_local_folder_syncs_into_hosted_memory() { + run_on_big_stack("hosted-folder-sync", || async { + let fx = Fixture::new().await; + bind_hosted(&fx).await; + let folder = fx._tmp.path().join("notes"); + std::fs::create_dir_all(&folder).expect("folder"); + std::fs::write(folder.join("tea.md"), "# Tea\n\nOolong, always.").expect("note"); + let v = fx + .call( + "openhuman.memory_sources_add", + json!({ + "kind": "folder", + "label": "Notes", + "enabled": true, + "path": folder.to_string_lossy(), + }), + ) + .await; + let source_id = result_of(&v, "add a folder source")["source"]["id"] + .as_str() + .expect("a source id") + .to_string(); + let v = fx + .call( + "openhuman.memory_sources_sync", + json!({ "source_id": source_id }), + ) + .await; + result_of(&v, "sync a folder on hosted"); + let synced = fx.hosted.events.lock().unwrap().iter().any(|event| { + event["scope"] == "tm:sources/tm:documents" + && event["content"]["text"] + .as_str() + .is_some_and(|text| text.contains("Oolong, always.")) + }); + assert!(synced, "the note reaches the hosted documents namespace"); + let v = fx + .call("openhuman.memory_sources_sync_audit_log", json!({})) + .await; + let history = result_of(&v, "sync history after a hosted folder sync"); + assert!( + history["entries"].to_string().contains(&source_id), + "{history}" + ); + unbind(&fx).await; + }); +} + +/// The first `documentId` anywhere in `value`. +fn document_id(value: &serde_json::Value) -> Option { + match value { + serde_json::Value::Object(map) => map + .get("documentId") + .and_then(serde_json::Value::as_str) + .map(str::to_string) + .or_else(|| map.values().find_map(document_id)), + serde_json::Value::Array(items) => items.iter().find_map(document_id), + _ => None, + } +} + +/// The families hosted memory serves beyond the mandatory ones, through the +/// app's RPCs: documents and tool rules round-trip. +#[test] +fn the_hosted_engine_serves_documents_and_tool_rules() { + run_on_big_stack("hosted-families", || async { + let fx = Fixture::new().await; + bind_hosted(&fx).await; + + let v = fx + .call( + "openhuman.memory_doc_put", + json!({ + "namespace": NS, "key": "tea", "title": "Tea", + "content": "The user drinks oolong.", "source_type": "doc", + "priority": "medium", "tags": [], "metadata": null, + "category": "core" + }), + ) + .await; + result_of(&v, "doc_put on hosted"); + let v = fx + .call("openhuman.memory_doc_list", json!({ "namespace": NS })) + .await; + let listed = result_of(&v, "doc_list on hosted").clone(); + assert!(listed.to_string().contains("Tea"), "{listed}"); + let id = document_id(&listed).unwrap_or_else(|| panic!("no document id: {listed}")); + let v = fx + .call( + "openhuman.memory_doc_delete", + json!({ "namespace": NS, "document_id": id }), + ) + .await; + let deleted = result_of(&v, "doc_delete on hosted"); + assert!( + deleted.to_string().contains("\"deleted\":true"), + "{deleted}" + ); + + let v = fx + .call( + "openhuman.memory_tool_rule_put", + json!({ "tool_name": "shell", "rule": "quote every path" }), + ) + .await; + result_of(&v, "tool_rule_put on hosted"); + let v = fx + .call( + "openhuman.memory_tool_rule_list", + json!({ "tool_name": "shell" }), + ) + .await; + let rules = result_of(&v, "tool_rule_list on hosted"); + assert!(rules.to_string().contains("quote every path"), "{rules}"); + + unbind(&fx).await; + }); +} + /// What the hosted engine does not serve answers cleanly: the RPCs that need /// a missing family name it, and the tree health reads degrade to an empty or /// unhealthy answer rather than an error. @@ -154,15 +323,6 @@ fn what_the_hosted_engine_does_not_serve_is_refused_cleanly() { json!({ "namespace": NS, "subject": "a", "predicate": "knows", "object": "b" }), ), ("openhuman.memory_graph_query", json!({ "namespace": NS })), - // memory_roundtrip_e2e - ( - "openhuman.memory_doc_put", - json!({ - "namespace": NS, "key": "k", "title": "t", "content": "c", - "source_type": "doc", "priority": "medium", "tags": [], - "metadata": null, "category": "core" - }), - ), ]; // Collected rather than asserted one by one, so a run names every // method that answers some other way. @@ -189,12 +349,14 @@ fn what_the_hosted_engine_does_not_serve_is_refused_cleanly() { .call("openhuman.memory_tree_list_sources", json!({})) .await; assert_eq!(result_of(&v, "tree list_sources on hosted"), &json!([])); + // Hosted memory serves Maintenance: the doctor answers from the + // service's health probe rather than naming a missing family. let v = fx.call("openhuman.memory_tree_doctor", json!({})).await; let doctor = result_of(&v, "tree doctor on hosted"); - assert_eq!(doctor["healthy"], false, "{doctor}"); + assert_eq!(doctor["healthy"], true, "{doctor}"); assert!( - doctor.to_string().contains("does not serve Maintenance"), - "the doctor names the missing family: {doctor}" + doctor.to_string().contains("\"service\""), + "the doctor reports the hosted service stage: {doctor}" ); let v = fx .call("openhuman.memory_tree_pipeline_status", json!({})) diff --git a/tests/raw_coverage/agent_orchestration_e2e.rs b/tests/raw_coverage/agent_orchestration_e2e.rs index a66aba0bff7..5cab0c8394e 100644 --- a/tests/raw_coverage/agent_orchestration_e2e.rs +++ b/tests/raw_coverage/agent_orchestration_e2e.rs @@ -788,64 +788,10 @@ async fn agent_team_list_and_close_reject_malformed_input() { /// drawer's row may be stale, and a stale row must not raise. `steer` goes /// further and says *why* it did nothing. #[tokio::test] -async fn subagent_cancel_and_steer_report_structurally_for_an_unknown_task() { +async fn subagent_steer_honours_and_defaults_the_queue_mode() { let _lock = env_lock(); let h = setup().await; - let cancelled = h - .ok( - 3501, - "openhuman.subagent_cancel", - json!({ "taskId": "sub-not-running" }), - ) - .await; - assert_eq!( - cancelled.get("cancelled").and_then(Value::as_bool), - Some(false), - "nothing was running, and that is an answer not a failure: {cancelled}" - ); - assert_eq!( - cancelled.get("taskId").and_then(Value::as_str), - Some("sub-not-running"), - "the answer echoes the task asked about: {cancelled}" - ); - - // A reason is accepted on the cancel path and must not change the verdict. - let with_reason = h - .ok( - 3502, - "openhuman.subagent_cancel", - json!({ "taskId": "sub-not-running", "reason": "changed my mind" }), - ) - .await; - assert_eq!( - with_reason.get("cancelled").and_then(Value::as_bool), - Some(false) - ); - - let steered = h - .ok( - 3503, - "openhuman.subagent_steer", - json!({ "taskId": "sub-not-running", "message": "focus on the failing test" }), - ) - .await; - assert_eq!( - steered.get("steered").and_then(Value::as_bool), - Some(false), - "an unknown task cannot be steered: {steered}" - ); - assert_eq!( - steered.get("reason").and_then(Value::as_str), - Some("unknown"), - "and the caller is told which of the failure modes it hit: {steered}" - ); - assert_eq!( - steered.get("mode").and_then(Value::as_str), - Some("steer"), - "steer is the default queue mode: {steered}" - ); - let collect = h .ok( 3504, @@ -880,62 +826,6 @@ async fn subagent_cancel_and_steer_report_structurally_for_an_unknown_task() { h.join.abort(); } -/// `taskId` is **trimmed** before it reaches the registry, so a whitespace- -/// padded id must be rejected up front — it would otherwise pass a naive -/// non-empty check and then silently never match a registry key. -#[tokio::test] -async fn subagent_controls_reject_blank_and_absent_required_params() { - let _lock = env_lock(); - let h = setup().await; - - // Each method gets its own param shape: the RPC layer rejects an unknown - // param, and `subagent_cancel` declares no `message`. - for (id, method, extra) in [ - (3601, "openhuman.subagent_cancel", json!({})), - (3602, "openhuman.subagent_steer", json!({ "message": "hi" })), - ] { - let mut blank = extra.as_object().cloned().expect("params object"); - blank.insert("taskId".to_string(), json!(" ")); - let blank = h.err(id, method, Value::Object(blank)).await; - assert!( - blank.contains("taskId"), - "{method} rejects a whitespace-only taskId: {blank}" - ); - - let absent = h.err(id + 10, method, extra).await; - assert!( - absent.contains("taskId"), - "{method} names its required taskId: {absent}" - ); - } - - let no_message = h - .err( - 3603, - "openhuman.subagent_steer", - json!({ "taskId": "sub-1" }), - ) - .await; - assert!( - no_message.contains("message"), - "steer names its required message: {no_message}" - ); - - let blank_message = h - .err( - 3604, - "openhuman.subagent_steer", - json!({ "taskId": "sub-1", "message": " " }), - ) - .await; - assert!( - blank_message.contains("message"), - "a blank steer message is treated as absent: {blank_message}" - ); - - h.join.abort(); -} - // ── agent_experience ──────────────────────────────────────────────────────── fn experience(id: &str, summary: &str, lesson: &str, tools: &[&str], tags: &[&str]) -> Value { diff --git a/tests/raw_coverage/app_credentials_threads_memory_sources_raw_coverage_e2e.rs b/tests/raw_coverage/app_credentials_threads_memory_sources_raw_coverage_e2e.rs deleted file mode 100644 index a44dab5fe8b..00000000000 --- a/tests/raw_coverage/app_credentials_threads_memory_sources_raw_coverage_e2e.rs +++ /dev/null @@ -1,237 +0,0 @@ -use std::collections::{BTreeMap, HashMap}; -use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex, OnceLock}; - -use chrono::Utc; -use openhuman_core::desktop::app_state::{ - snapshot, update_local_state, StoredAppStatePatch, StoredOnboardingTasks, -}; -use openhuman_core::config::Config; -use openhuman_core::config::rpc as config_rpc; -use openhuman_core::security::credentials::profiles::{ - profile_id, AuthProfile, AuthProfilesStore, TokenSet, -}; -use openhuman_core::security::credentials::{ - list_provider_credentials_by_prefix, AuthService, APP_SESSION_PROVIDER, - DEFAULT_AUTH_PROFILE_NAME, -}; -use openhuman_core::memory::{ - AppendConversationMessageRequest, ConversationMessageRecord, ConversationMessagesRequest, - CreateConversationThreadRequest, DeleteConversationThreadRequest, EmptyRequest, - GenerateConversationThreadTitleRequest, UpdateConversationMessageRequest, - UpdateConversationThreadLabelsRequest, UpdateConversationThreadTitleRequest, -}; -use openhuman_core::memory::sources::readers::SourceReader; -use openhuman_core::memory::sources::{ - self as memory_sources, MemorySourceEntry, MemorySourcePatch, SourceKind, -}; -use openhuman_core::threads::{migrate_welcome_agent_artifacts, ops as thread_ops}; -use serde_json::{json, Value}; -use tempfile::{Builder, TempDir}; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; - -static ROUND19_ENV_LOCK: &OnceLock> = &crate::SHARED_ENV_LOCK; -static MEMORY_SEAMS_INIT: OnceLock<()> = OnceLock::new(); - -fn ensure_memory_seams() { - MEMORY_SEAMS_INIT.get_or_init(|| { - std::thread::Builder::new() - .name("round19-memory-source-seams".to_string()) - .stack_size(8 * 1024 * 1024) - .spawn(|| { - }) - .expect("spawn round19 memory source seam installer") - .join() - .expect("round19 memory source seam installer panicked"); - }); -} - -struct EnvGuard { - key: &'static str, - old: Option, -} - -impl EnvGuard { - fn set(key: &'static str, value: &str) -> Self { - let old = std::env::var(key).ok(); - std::env::set_var(key, value); - Self { key, old } - } - - fn set_to_path(key: &'static str, path: &Path) -> Self { - let old = std::env::var(key).ok(); - std::env::set_var(key, path.as_os_str()); - Self { key, old } - } - - fn unset(key: &'static str) -> Self { - let old = std::env::var(key).ok(); - std::env::remove_var(key); - Self { key, old } - } -} - -impl Drop for EnvGuard { - fn drop(&mut self) { - match &self.old { - Some(value) => std::env::set_var(self.key, value), - None => std::env::remove_var(self.key), - } - } -} - -struct Harness { - _tmp: TempDir, - root: PathBuf, - _guards: Vec, -} - -impl Harness { - async fn config(&self) -> openhuman_core::config::Config { - config_rpc::load_config_with_timeout() - .await - .expect("isolated config should load") - } - - fn workspace_dir(&self) -> PathBuf { - self.root.join("workspace") - } - - fn state_dir(&self) -> PathBuf { - self.workspace_dir().join("state") - } - - fn app_state_file(&self) -> PathBuf { - self.state_dir().join("app-state.json") - } -} - -fn env_lock() -> std::sync::MutexGuard<'static, ()> { - ROUND19_ENV_LOCK - .get_or_init(|| Mutex::new(())) - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) -} - -fn tempdir() -> TempDir { - std::fs::create_dir_all("target").expect("create target"); - Builder::new() - .prefix("app-credentials-threads-memory-sources-round19-") - .tempdir_in("target") - .expect("round19 tempdir") -} - -fn write_min_config(root: &Path, api_url: &str) { - std::fs::create_dir_all(root).expect("create config root"); - let cfg = format!( - r#"api_url = "{api_url}" -default_model = "round19-coverage-model" -default_temperature = 0.2 -onboarding_completed = true -chat_onboarding_completed = false - -[observability] -analytics_enabled = true - -[secrets] -encrypt = false - -[meet] -auto_orchestrator_handoff = true - -[local_ai] -enabled = false -runtime_enabled = false -opt_in_confirmed = false - -[memory] -provider = "none" -embedding_provider = "none" -embedding_model = "none" -embedding_dimensions = 0 -auto_save = false - -[memory_tree] -embedding_strict = false -"# - ); - std::fs::write(root.join("config.toml"), &cfg).expect("write config.toml"); - let _: openhuman_core::config::Config = - toml::from_str(&cfg).expect("round19 config must match schema"); -} - -fn setup(api_url: &str) -> Harness { - let tmp = tempdir(); - let root = tmp.path().join("openhuman"); - write_min_config(&root, api_url); - let guards = vec![ - EnvGuard::set_to_path("OPENHUMAN_WORKSPACE", &root), - EnvGuard::set_to_path("HOME", tmp.path()), - EnvGuard::unset("BACKEND_URL"), - EnvGuard::unset("VITE_BACKEND_URL"), - EnvGuard::unset("OPENHUMAN_API_URL"), - EnvGuard::unset("OPENHUMAN_CORE_RPC_URL"), - EnvGuard::unset("OPENHUMAN_CORE_PORT"), - EnvGuard::set("OPENHUMAN_KEYRING_BACKEND", "file"), - EnvGuard::set("OPENHUMAN_MEMORY_EMBED_STRICT", "false"), - EnvGuard::set("OPENHUMAN_MEMORY_EMBED_ENDPOINT", ""), - EnvGuard::set("OPENHUMAN_MEMORY_EMBED_MODEL", ""), - ]; - - Harness { - _tmp: tmp, - root, - _guards: guards, - } -} - -fn source_entry(id: &str, kind: SourceKind, label: &str) -> MemorySourceEntry { - MemorySourceEntry { - id: id.to_string(), - kind, - label: label.to_string(), - enabled: true, - toolkit: None, - connection_id: None, - path: None, - glob: None, - url: None, - branch: None, - paths: Vec::new(), - query: None, - since_days: None, - max_items: None, - max_commits: None, - max_issues: None, - max_prs: None, - selector: None, - max_tokens_per_sync: None, - max_cost_per_sync_usd: None, - sync_depth_days: None, - } -} - -async fn one_response_server( - body: &'static str, - content_type: &'static str, -) -> (String, tokio::task::JoinHandle<()>) { - let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)) - .await - .expect("bind fixture listener"); - let url = format!("http://{}", listener.local_addr().expect("listener addr")); - let task = tokio::spawn(async move { - if let Ok((mut stream, _)) = listener.accept().await { - let mut req = [0_u8; 2048]; - let _ = stream.read(&mut req).await; - let response = format!( - "HTTP/1.1 200 OK\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}", - body.len(), - body - ); - let _ = stream.write_all(response.as_bytes()).await; - let _ = stream.shutdown().await; - } - }); - (url, task) -} - diff --git a/tests/raw_coverage/automation_scheduling_e2e.rs b/tests/raw_coverage/automation_scheduling_e2e.rs index 4eb58582e11..98ac0fe6d92 100644 --- a/tests/raw_coverage/automation_scheduling_e2e.rs +++ b/tests/raw_coverage/automation_scheduling_e2e.rs @@ -425,63 +425,6 @@ async fn cron_run_records_history_and_remove_is_not_idempotent() { h.join.abort(); } -/// Every cron controller validates its `job_id` before touching the store, and -/// a whitespace-only id must not slip through as a valid one. -#[tokio::test] -async fn cron_controllers_reject_absent_and_blank_job_ids() { - let _lock = env_lock(); - let h = setup().await; - - for (id, method) in [ - (2101, "openhuman.cron_remove"), - (2102, "openhuman.cron_run"), - (2103, "openhuman.cron_runs"), - ] { - let blank = h.err(id, method, json!({ "job_id": " " })).await; - assert!( - blank.contains("job_id"), - "{method} rejects a blank job_id by name: {blank}" - ); - - let absent = h.err(id + 10, method, json!({})).await; - assert!( - absent.contains("job_id"), - "{method} names its required param: {absent}" - ); - } - - // The three diverge on an id that does not name a job, and the divergence - // is worth pinning. `remove` and `run` both go through `cron::get_job` / - // `remove_job` and raise; `runs` queries the run table by id and cannot - // tell "no such job" from "job with no runs", so a typo reads as an empty - // history. See `~/tinyhuman/bugs/e2e-wave-cron-run-schema-declares-an-outcome-it-never-returns.md`. - for (id, method) in [ - (2121, "openhuman.cron_remove"), - (2122, "openhuman.cron_run"), - ] { - let unknown = h.err(id, method, json!({ "job_id": "no-such-job" })).await; - assert!( - unknown.contains("no-such-job"), - "{method} names the unknown job: {unknown}" - ); - } - - let unknown_history = h - .ok( - 2123, - "openhuman.cron_runs", - json!({ "job_id": "no-such-job" }), - ) - .await; - assert_eq!( - unknown_history.as_array().map(Vec::len), - Some(0), - "cron_runs cannot distinguish an unknown job from one with no runs: {unknown_history}" - ); - - h.join.abort(); -} - // ── task_sources ──────────────────────────────────────────────────────────── /// `task_sources_sync` fans out over every ENABLED source and reports one diff --git a/tests/raw_coverage/channels_lark_email_dispatch_round21_raw_coverage_e2e.rs b/tests/raw_coverage/channels_lark_email_dispatch_round21_raw_coverage_e2e.rs index 0c1b3079d48..90baac0f82d 100644 --- a/tests/raw_coverage/channels_lark_email_dispatch_round21_raw_coverage_e2e.rs +++ b/tests/raw_coverage/channels_lark_email_dispatch_round21_raw_coverage_e2e.rs @@ -1,95 +1,10 @@ //! Round21 raw integration coverage for channels provider seams. //! -//! Loopback servers and parser fixtures only: no real Discord, Lark, IMAP, or -//! SMTP traffic is performed. +//! Parser fixtures only: no real IMAP or SMTP traffic is performed. -use axum::{extract::Path, http::StatusCode, routing::get, Json, Router}; -use openhuman_core::channels::providers::discord::api::test_support as discord_support; use openhuman_core::channels::providers::email_channel::{ test_support as email_support, EmailChannel, EmailConfig, }; -use openhuman_core::channels::providers::lark::test_support as lark_support; -use openhuman_core::channels::test_support::{ - run_dispatch_harness, DispatchHarnessOptions, TestMemoryEntry, -}; -use openhuman_core::channels::LarkChannel; -use serde_json::json; -// Lark's WS seam lives in tinychannels (tungstenite 0.29); use its re-export so -// the message type matches the function signature across the version boundary. -use tinychannels::tokio_tungstenite::tungstenite::Message as WsMsg; - -async fn spawn_mock(app: Router) -> String { - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("bind mock"); - let addr = listener.local_addr().expect("mock addr"); - tokio::spawn(async move { - axum::serve(listener, app).await.expect("serve mock"); - }); - format!("http://127.0.0.1:{}", addr.port()) -} - -#[test] -fn lark_parser_support_covers_post_mentions_placeholders_and_webhook_payloads() { - let rich_post = json!({ - "fr_fr": { - "title": "Incident digest", - "content": [[ - {"tag": "text", "text": "See "}, - {"tag": "a", "href": "https://status.example.test/42"}, - {"tag": "at", "user_id": "ou_alice"}, - {"tag": "unknown", "text": "ignored"} - ]] - } - }) - .to_string(); - let post_text = lark_support::parse_post_content_for_test(&rich_post).expect("post text"); - assert!(post_text.contains("Incident digest")); - assert!(post_text.contains("https://status.example.test/42")); - assert!(post_text.contains("@ou_alice")); - assert!(lark_support::parse_post_content_for_test("{}").is_none()); - - assert_eq!( - lark_support::strip_at_placeholders_for_test("@_user_1 please review @_user_99 now"), - "please review now" - ); - assert!(!lark_support::should_respond_in_group_for_test(&[])); - assert!(lark_support::should_respond_in_group_for_test(&[ - json!({"name": "OpenHuman"}) - ])); - assert!(lark_support::should_refresh_last_recv_for_test( - &WsMsg::Binary(vec![1, 2, 3].into()) - )); - assert!(!lark_support::should_refresh_last_recv_for_test( - &WsMsg::Text("not heartbeat".into()) - )); - - let channel = LarkChannel::new( - "app".into(), - "secret".into(), - "verify".into(), - None, - vec!["ou_allowed".into()], - ); - let payload = json!({ - "header": {"event_type": "im.message.receive_v1"}, - "event": { - "sender": {"sender_id": {"open_id": "ou_allowed"}}, - "message": { - "message_type": "post", - "content": rich_post, - "chat_id": "oc_round21", - "create_time": "1700000000123" - } - } - }); - let messages = channel.parse_event_payload(&payload); - assert_eq!(messages.len(), 1); - assert_eq!(messages[0].channel, "lark"); - assert_eq!(messages[0].reply_target, "oc_round21"); - assert_eq!(messages[0].timestamp, 1_700_000_000); - assert!(messages[0].content.contains("Incident digest")); -} #[test] fn email_parser_support_covers_text_html_attachment_and_message_building() { @@ -126,106 +41,3 @@ fn email_parser_support_covers_text_html_attachment_and_message_building() { assert!(wire.contains("Subject: Round21")); assert!(wire.contains("coverage body")); } - -#[tokio::test] -async fn discord_permission_check_covers_member_overwrite_and_bot_lookup_failure() { - // Guild/channel listing and the 401 rewrap are covered in - // `vendor/tinychannels/src/providers/discord/api_tests.rs`; this keeps the - // role-overwrite + member-overwrite combination and the `get_bot_user` failure. - let permission_app = Router::new() - .route("/users/@me", get(|| async { Json(json!({"id": "bot-1"})) })) - .route( - "/guilds/{guild_id}/members/{member_id}", - get( - |Path((_guild_id, member_id)): Path<(String, String)>| async move { - assert_eq!(member_id, "bot-1"); - Json(json!({"roles": ["role-send"], "user": {"id": "bot-1"}})) - }, - ), - ) - .route( - "/guilds/{guild_id}/roles", - get(|Path(guild_id): Path| async move { - Json(json!([ - {"id": guild_id, "permissions": "1024"}, - {"id": "role-send", "permissions": "2048"} - ])) - }), - ) - .route( - "/channels/{channel_id}", - get(|Path(channel_id): Path| async move { - assert_eq!(channel_id, "c1"); - Json(json!({ - "permission_overwrites": [ - {"id": "role-send", "type": 0, "allow": "65536", "deny": "2048"}, - {"id": "bot-1", "type": 1, "allow": "2048", "deny": "0"} - ] - })) - }), - ); - let base = spawn_mock(permission_app).await; - let check = - discord_support::check_channel_permissions_at_base_for_test(&base, "token", "g1", "c1") - .await - .expect("permission check"); - assert!(check.can_view_channel); - assert!(check.can_send_messages); - assert!(check.can_read_message_history); - assert!(check.missing_permissions.is_empty()); - - let failing_app = Router::new().route( - "/users/@me", - get(|| async { (StatusCode::BAD_GATEWAY, "discord unavailable") }), - ); - let base = spawn_mock(failing_app).await; - let err = - discord_support::check_channel_permissions_at_base_for_test(&base, "token", "g1", "c1") - .await - .expect_err("me lookup fails") - .to_string(); - assert!(err.contains("get_bot_user")); - assert!(err.contains("502")); -} - -#[tokio::test] -async fn dispatch_harness_round21_covers_non_web_context_success_and_timeout() { - let observed = run_dispatch_harness(DispatchHarnessOptions { - channel_name: "lark".to_string(), - content: "thanks, can you summarize remembered channel state?".to_string(), - thread_ts: Some("lark-thread".to_string()), - supports_reactions: true, - memory_entries: vec![TestMemoryEntry { - key: "round21".to_string(), - content: "Lark messages include reply target context.".to_string(), - score: Some(0.95), - }], - response_text: Some("lark dispatch response".to_string()), - ..Default::default() - }) - .await; - assert_eq!(observed.handler_channel_name, "lark"); - assert!(observed.handler_history_text.contains("[Channel context]")); - assert!(observed.handler_history_text.contains("[Memory context]")); - assert!(observed - .sends - .iter() - .any(|send| send.kind == "send" && send.content.starts_with("[REACTION:"))); - assert!(observed - .sends - .iter() - .any(|send| send.content == "lark dispatch response")); - - let timed_out = run_dispatch_harness(DispatchHarnessOptions { - channel_name: "email".to_string(), - content: "force timeout".to_string(), - handler_delay_ms: 1_200, - timeout_secs: 1, - ..Default::default() - }) - .await; - assert!(timed_out - .sends - .iter() - .any(|send| send.content.contains("Request timed out"))); -} diff --git a/tests/raw_coverage/channels_round24_raw_coverage_e2e.rs b/tests/raw_coverage/channels_round24_raw_coverage_e2e.rs index 49401515719..fb02f993443 100644 --- a/tests/raw_coverage/channels_round24_raw_coverage_e2e.rs +++ b/tests/raw_coverage/channels_round24_raw_coverage_e2e.rs @@ -4,8 +4,6 @@ use openhuman_core::channels::bus::test_support as bus_support; use openhuman_core::channels::providers::email_channel::test_support as email_support; -use openhuman_core::channels::providers::lark::test_support as lark_support; -use openhuman_core::channels::providers::telegram::test_support as telegram_support; use openhuman_core::channels::test_support as runtime_support; use openhuman_core::channels::traits::ChannelMessage; use serde_json::json; @@ -98,27 +96,7 @@ fn dispatch_helpers_cover_channel_context_and_ack_categories() { } #[test] -fn lark_and_email_parser_edges_are_exercised_without_sockets() { - let rich_post = json!({ - "en_us": { - "content": [[ - {"tag": "a", "href": "https://example.test/fallback"}, - {"tag": "at", "user_id": "ou_123"}, - {"tag": "text", "text": " done"} - ]] - } - }) - .to_string(); - let parsed = lark_support::parse_post_content_for_test(&rich_post).expect("post text"); - assert!(parsed.contains("https://example.test/fallback")); - assert!(parsed.contains("@ou_123")); - assert!(parsed.ends_with("done")); - assert!(lark_support::parse_post_content_for_test("not json").is_none()); - assert_eq!( - lark_support::strip_at_placeholders_for_test("before @_user_123 after @_user_x"), - "before after @_user_x" - ); - +fn email_parser_edges_are_exercised_without_sockets() { let no_sender = b"Subject: Anonymous\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nbody"; let parsed_mail = email_support::parse_email_fixture(no_sender).expect("mail parse"); assert_eq!(parsed_mail.sender, "unknown"); @@ -129,23 +107,3 @@ fn lark_and_email_parser_edges_are_exercised_without_sockets() { let parsed_html = email_support::parse_email_fixture(html_only).expect("html parse"); assert_eq!(parsed_html.text, "A\nB\n"); } - -#[test] -fn telegram_reaction_marker_parser_covers_malformed_and_inline_forms() { - assert_eq!( - telegram_support::parse_reaction_marker_for_test("plain text"), - ("plain text".to_string(), None) - ); - assert_eq!( - telegram_support::parse_reaction_marker_for_test("[REACTION:]"), - (String::new(), None) - ); - assert_eq!( - telegram_support::parse_reaction_marker_for_test("[REACTION:ok"), - ("[REACTION:ok".to_string(), None) - ); - assert_eq!( - telegram_support::parse_reaction_marker_for_test(" [REACTION:ok|123] reply body "), - ("reply body".to_string(), Some("ok|123".to_string())) - ); -} diff --git a/tests/raw_coverage/channels_round26_raw_coverage_e2e.rs b/tests/raw_coverage/channels_round26_raw_coverage_e2e.rs index 7c6fec2f1e7..9c7bda6efb1 100644 --- a/tests/raw_coverage/channels_round26_raw_coverage_e2e.rs +++ b/tests/raw_coverage/channels_round26_raw_coverage_e2e.rs @@ -1,6 +1,6 @@ //! Round26 raw integration coverage for high-yield channel cold paths. //! -//! Loopback Bot API endpoints and parser/codec fixtures only: no real channel +//! Loopback Bot API endpoints only: no real channel //! network services are contacted. //! //! Yuanbao biz-codec cases live in `vendor/tinychannels` (`yuanbao/proto_biz.rs`). @@ -12,10 +12,6 @@ use axum::{ routing::post, Json, Router, }; -use openhuman_core::channels::providers::email_channel::{ - test_support as email_support, EmailChannel, EmailConfig, -}; -use openhuman_core::channels::providers::irc::test_support as irc_support; use openhuman_core::channels::providers::telegram::TelegramChannel; use openhuman_core::channels::traits::{Channel, SendMessage}; use serde_json::{json, Value}; @@ -285,72 +281,3 @@ async fn telegram_loopback_covers_reaction_text_fallback_and_media_send_paths() assert_eq!(multipart[1].0, "sendPhoto"); assert!(multipart[1].1.contains("round26.png")); } - -#[test] -fn irc_and_email_parser_edges_cover_helpers_without_sockets() { - let parsed = irc_support::parse_line_for_test(":Alice!u@h PRIVMSG #ops :hello world") - .expect("irc privmsg parse"); - assert_eq!(parsed.0.as_deref(), Some("Alice!u@h")); - assert_eq!(parsed.1, "PRIVMSG"); - assert_eq!( - parsed.2, - vec!["#ops".to_string(), "hello world".to_string()] - ); - assert_eq!(parsed.3.as_deref(), Some("Alice")); - assert_eq!( - irc_support::parse_line_for_test("PING :server") - .expect("ping parse") - .2, - vec!["server".to_string()] - ); - assert!(irc_support::parse_line_for_test("").is_none()); - assert_eq!( - irc_support::encode_sasl_plain_for_test("openhuman", "secret"), - "AG9wZW5odW1hbgBzZWNyZXQ=" - ); - assert!(irc_support::is_user_allowed_for_test( - vec!["*".to_string()], - "Anyone" - )); - assert!(irc_support::is_user_allowed_for_test( - vec!["Alice".to_string()], - "alice" - )); - assert!(!irc_support::is_user_allowed_for_test( - vec!["Alice".to_string()], - "bob" - )); - - let chunks = irc_support::split_message_for_test("alpha\nβeta\r\n0123456789", 5); - assert_eq!(chunks, vec!["alpha", "βeta", "01234", "56789"]); - assert_eq!( - irc_support::split_message_for_test("\n", 0), - vec![String::new()] - ); - - let channel = EmailChannel::new(EmailConfig { - from_address: "bot@example.test".to_string(), - allowed_senders: vec![ - "*".to_string(), - "admin@example.test".to_string(), - "@team.example".to_string(), - ], - ..Default::default() - }); - assert!(channel.is_sender_allowed("blocked@anywhere.test")); - assert_eq!( - EmailChannel::strip_html("
hello
team
"), - "helloteam" - ); - let no_body = b"From: Unknown \r\nSubject: No Body\r\n\r\n"; - let parsed = email_support::parse_email_fixture(no_body).expect("email parse"); - assert_eq!(parsed.sender, "nobody@example.test"); - assert_eq!(parsed.subject.as_deref(), Some("No Body")); - assert!(parsed.text.is_empty()); - let plain = channel - .build_plain_message("ops@example.test", "Round26", "plain body") - .expect("plain email"); - let formatted = String::from_utf8_lossy(&plain.formatted()).to_string(); - assert!(formatted.contains("Subject: Round26")); - assert!(formatted.contains("plain body")); -} diff --git a/tests/raw_coverage/composio_raw_coverage_e2e.rs b/tests/raw_coverage/composio_raw_coverage_e2e.rs index 12836a4bef6..107b92a7421 100644 --- a/tests/raw_coverage/composio_raw_coverage_e2e.rs +++ b/tests/raw_coverage/composio_raw_coverage_e2e.rs @@ -5,12 +5,6 @@ use std::sync::{Arc, Mutex, OnceLock}; -use axum::body::to_bytes; -use axum::extract::{Request, State}; -use axum::http::{Method, StatusCode}; -use axum::response::{IntoResponse, Response}; -use axum::routing::any; -use axum::{Json, Router}; use serde_json::{json, Value}; use tempfile::tempdir; @@ -18,36 +12,14 @@ use openhuman_core::agent::prompts::ConnectedIntegration; use openhuman_core::config::Config; use openhuman_core::core::all::RegisteredController; use openhuman_core::integrations::composio::client::{resolve_composio_route, ComposioRoute}; -use openhuman_core::integrations::composio::providers::{ - classify_unknown, find_curated, toolkit_from_slug, CuratedTool, ToolScope, UserScopePref, -}; -use openhuman_core::integrations::composio::tools::{ - ComposioAuthorizeTool, ComposioConnectedAccount, ComposioExecuteTool, - ComposioListConnectionsTool, ComposioListToolkitsTool, ComposioListToolsTool, -}; -use openhuman_core::integrations::composio::types::{ - ComposioActiveTrigger, ComposioActiveTriggersResponse, ComposioAgentReadyToolkitsResponse, - ComposioAuthorizeResponse, ComposioAvailableTrigger, ComposioAvailableTriggerRepo, - ComposioAvailableTriggersResponse, ComposioCapabilitiesResponse, ComposioCapability, - ComposioConnection, ComposioConnectionsResponse, ComposioCreateTriggerResponse, - ComposioDeleteResponse, ComposioDisableTriggerResponse, ComposioEnableTriggerResponse, - ComposioExecuteResponse, ComposioGithubRepo, ComposioGithubReposResponse, ComposioToolFunction, - ComposioToolSchema, ComposioToolkitsResponse, ComposioToolsResponse, ComposioTriggerEvent, - ComposioTriggerHistoryEntry, ComposioTriggerHistoryResult, ComposioTriggerMetadata, -}; use openhuman_core::integrations::composio::{ - all_composio_agent_tools, all_composio_controller_schemas, all_composio_registered_controllers, + all_composio_controller_schemas, all_composio_registered_controllers, cached_active_integrations, connected_set_hash, connection_identity, fetch_connected_integrations, fetch_connected_integrations_status, invalidate_connected_integrations_cache, ComposioActionTool, FetchConnectedIntegrationsStatus, }; -use openhuman_core::security::credentials::{ - AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME, -}; -use openhuman_core::integrations::IntegrationClient; -use openhuman_core::security::{AutonomyLevel, SecurityPolicy}; -use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolCategory}; +use tinytools::Tool; static ENV_LOCK: &OnceLock> = &crate::SHARED_ENV_LOCK; @@ -168,46 +140,6 @@ async fn composio_ops_mode_is_local_and_trigger_history_reflects_module_archive_ } } -#[test] -fn composio_action_tool_metadata_is_stable_without_network_execution() { - crate::tinyhumans_boot::boot(); - let dir = tempdir().expect("tempdir"); - let config = Config { - workspace_dir: dir.path().to_path_buf(), - config_path: dir.path().join("config.toml"), - ..Config::default() - }; - let tool = ComposioActionTool::new( - Arc::new(config), - "GMAIL_SEND_EMAIL".into(), - "Send an email".into(), - Some(json!({ - "type": "object", - "properties": { "to": { "type": "string" } } - })), - ); - - assert_eq!(tool.name(), "GMAIL_SEND_EMAIL"); - assert_eq!(tool.description(), "Send an email"); - assert_eq!(tool.permission_level(), PermissionLevel::Write); - assert_eq!(tool.category(), ToolCategory::Workflow); - assert_eq!( - tool.parameters_schema().pointer("/properties/to/type"), - Some(&json!("string")) - ); - - let default_schema = ComposioActionTool::new( - Arc::new(Config::default()), - "NOTION_FETCH_DATA".into(), - "Fetch Notion data".into(), - None, - ); - assert_eq!( - default_schema.parameters_schema(), - json!({ "type": "object" }) - ); -} - #[tokio::test] async fn composio_action_tool_execute_reports_missing_route_without_network() { let _module = crate::CONNECTOR_MODULE_LOCK.lock().await; @@ -269,24 +201,6 @@ fn composio_client_factory_modes_are_deterministic_without_network() { assert!(unknown.to_string().contains("unknown composio mode")); } -#[test] -fn composio_backend_route_resolves_from_stored_session() { - crate::tinyhumans_boot::boot(); - let dir = tempdir().expect("tempdir"); - let mut config = Config { - workspace_dir: dir.path().join("workspace"), - config_path: dir.path().join("config.toml"), - api_url: Some("http://127.0.0.1:0".into()), - ..Config::default() - }; - config.composio.mode = "backend".into(); - store_app_session_token(&config, " stored-session-token "); - - let route = resolve_composio_route(&config).expect("backend route from stored session"); - assert!(matches!(route, ComposioRoute::Backend)); - assert_eq!(route.mode(), "backend"); -} - #[tokio::test] async fn composio_controller_registry_and_scope_handlers_cover_validation_edges() { let _env_lock = ENV_LOCK @@ -564,745 +478,3 @@ async fn composio_call(controller: &RegisteredController, params: Value) -> Resu (controller.handler)(params).await } -#[tokio::test] -async fn composio_agent_tools_cover_metadata_missing_params_and_scope_helpers() { - let _module = crate::CONNECTOR_MODULE_LOCK.lock().await; - crate::tinyhumans_boot::boot(); - let dir = tempdir().expect("tempdir"); - let config = Config { - workspace_dir: dir.path().to_path_buf(), - config_path: dir.path().join("config.toml"), - ..Config::default() - }; - let config = Arc::new(config); - - let list_toolkits = ComposioListToolkitsTool::new(config.clone()); - assert_eq!(list_toolkits.name(), "composio_list_toolkits"); - assert_eq!(list_toolkits.permission_level(), PermissionLevel::ReadOnly); - assert_eq!(list_toolkits.category(), ToolCategory::Workflow); - assert_eq!( - list_toolkits - .parameters_schema() - .pointer("/additionalProperties"), - Some(&json!(false)) - ); - - let list_connections = ComposioListConnectionsTool::new(config.clone()); - assert_eq!(list_connections.name(), "composio_list_connections"); - assert_eq!( - list_connections.permission_level(), - PermissionLevel::ReadOnly - ); - assert_eq!(list_connections.category(), ToolCategory::Workflow); - - let authorize = ComposioAuthorizeTool::new(config.clone()); - assert_eq!(authorize.name(), "composio_authorize"); - assert_eq!(authorize.permission_level(), PermissionLevel::Write); - assert_eq!( - authorize.parameters_schema().pointer("/required/0"), - Some(&json!("toolkit")) - ); - let auth_missing = authorize.execute(json!({})).await.expect("missing toolkit"); - assert!(auth_missing.is_error); - assert!(serde_json::to_string(&auth_missing) - .unwrap() - .contains("'toolkit' is required")); - - let list_tools = ComposioListToolsTool::new(config.clone()); - assert_eq!(list_tools.name(), "composio_list_tools"); - assert!(list_tools.supports_markdown()); - assert_eq!( - list_tools - .parameters_schema() - .pointer("/properties/tags/items/type"), - Some(&json!("string")) - ); - - let execute = ComposioExecuteTool::new(config.clone()); - assert_eq!(execute.name(), "composio_execute"); - assert_eq!(execute.permission_level(), PermissionLevel::Write); - assert_eq!(execute.category(), ToolCategory::Workflow); - let execute_missing = execute.execute(json!({})).await.expect("missing tool"); - assert!(execute_missing.is_error); - assert!(serde_json::to_string(&execute_missing) - .unwrap() - .contains("'tool' is required")); - - let mut direct_config = (*config).clone(); - direct_config.composio.mode = "direct".to_string(); - direct_config.composio.api_key = Some("test-direct-key".to_string()); - let registered_tools = all_composio_agent_tools(&direct_config); - let names: Vec<&str> = registered_tools.iter().map(|tool| tool.name()).collect(); - assert_eq!( - names, - vec![ - "composio_list_toolkits", - "composio_list_connections", - "composio_authorize", - "composio_connect", - "composio_list_tools", - "composio_execute", - ] - ); - let anonymous_config_dir = tempfile::tempdir().expect("anonymous config directory"); - let mut anonymous_config = Config::default(); - anonymous_config.config_path = anonymous_config_dir.path().join("config.toml"); - let no_tools = all_composio_agent_tools(&anonymous_config); - assert!(no_tools.is_empty()); - - assert_eq!( - toolkit_from_slug(" GMAIL_SEND_EMAIL "), - Some("gmail".into()) - ); - assert_eq!( - toolkit_from_slug("noUnderscore"), - Some("nounderscore".into()) - ); - assert_eq!(toolkit_from_slug(""), None); - assert_eq!(classify_unknown("GMAIL_DELETE_EMAIL"), ToolScope::Admin); - assert_eq!(classify_unknown("GMAIL_SEND_EMAIL"), ToolScope::Write); - assert_eq!(classify_unknown("GMAIL_FETCH_EMAILS"), ToolScope::Read); - let catalog = [ - CuratedTool { - slug: "GMAIL_FETCH_EMAILS", - scope: ToolScope::Read, - }, - CuratedTool { - slug: "GMAIL_SEND_EMAIL", - scope: ToolScope::Write, - }, - ]; - assert_eq!( - find_curated(&catalog, "gmail_send_email") - .expect("case-insensitive curated match") - .scope, - ToolScope::Write - ); - assert!(find_curated(&catalog, "GMAIL_DELETE_EMAIL").is_none()); - assert_eq!(ToolScope::Admin.as_str(), "admin"); - let pref = UserScopePref { - read: true, - write: false, - admin: false, - }; - assert!(pref.allows(ToolScope::Read)); - assert!(!pref.allows(ToolScope::Write)); - assert!(!pref.allows(ToolScope::Admin)); - - let fallback = list_tools - .execute_with_options( - json!({ "toolkits": ["unknown_toolkit"], "include_unconnected": true }), - ToolCallOptions { - prefer_markdown: true, - }, - ) - .await - .expect("factory failure is rendered as tool result"); - assert!(fallback.is_error); -} - -#[tokio::test] -async fn composio_agent_tools_direct_mode_take_local_branches_without_backend() { - let _module = crate::CONNECTOR_MODULE_LOCK.lock().await; - crate::tinyhumans_boot::boot(); - let dir = tempdir().expect("tempdir"); - let mut config = Config { - workspace_dir: dir.path().join("workspace"), - config_path: dir.path().join("config.toml"), - ..Config::default() - }; - config.composio.mode = "direct".into(); - config.composio.api_key = Some("direct-test-key".into()); - config - .save() - .await - .expect("persist direct-mode test config"); - let config = Arc::new(config); - - let list_toolkits = ComposioListToolkitsTool::new(config.clone()); - let toolkits = list_toolkits - .execute(json!({})) - .await - .expect("direct list_toolkits returns local empty response"); - assert!(!toolkits.is_error); - assert_eq!(toolkits.text(), r#"{"toolkits":[]}"#); - - let list_tools = ComposioListToolsTool::new(config.clone()); - let tools = list_tools - .execute_with_options( - json!({ "include_unconnected": true, "tags": ["ignored outside github"] }), - ToolCallOptions { - prefer_markdown: true, - }, - ) - .await - .expect("direct list_tools returns local empty response"); - assert!(!tools.is_error); - assert_eq!(tools.text(), r#"{"tools":[]}"#); - assert_eq!( - tools.markdown_formatted.as_deref(), - Some("_No composio tools available._") - ); - - let authorize = ComposioAuthorizeTool::new(config.clone()); - let authorize_result = authorize - .execute(json!({ "toolkit": "gmail" })) - .await - .expect("direct authorize is refused locally"); - assert!(authorize_result.is_error); - assert!(authorize_result.text().contains("direct mode is active")); - - let execute = ComposioExecuteTool::new(config); - let execute_result = execute - .execute(json!({ - "tool": "GMAIL_FETCH_EMAILS", - "connection_id": "conn-gmail", - "arguments": "not an object" - })) - .await - .expect("direct execute validation is rendered locally"); - assert!(execute_result.is_error); - let execute_text = execute_result.text(); - assert!( - execute_text.starts_with("[composio:error:"), - "{execute_text}" - ); - assert!(execute_text.contains("must be a JSON object")); -} - -#[test] -fn composio_types_roundtrip_connection_tool_trigger_and_history_shapes() { - crate::tinyhumans_boot::boot(); - let toolkits: ComposioToolkitsResponse = serde_json::from_value(json!({})).unwrap(); - assert!(toolkits.toolkits.is_empty()); - - let agent_ready = ComposioAgentReadyToolkitsResponse { - toolkits: vec!["gmail".into(), "googlesheets".into()], - }; - assert_eq!( - serde_json::to_value(&agent_ready).unwrap()["toolkits"][1], - "googlesheets" - ); - - let authorize = ComposioAuthorizeResponse { - connect_url: "https://connect.example/oauth".into(), - connection_id: "conn-123".into(), - }; - let authorize_json = serde_json::to_value(&authorize).unwrap(); - assert_eq!( - authorize_json["connectUrl"], - "https://connect.example/oauth" - ); - assert_eq!(authorize_json["connectionId"], "conn-123"); - - let capabilities = ComposioCapabilitiesResponse { - capabilities: vec![ComposioCapability { - toolkit: "gmail".into(), - description: "Gmail".into(), - native_provider: true, - curated_tools: true, - curated_tool_count: 3, - tool_execution: true, - user_profile: true, - initial_sync: true, - periodic_sync: true, - sync_interval_secs: Some(3600), - trigger_webhooks: true, - memory_ingest: true, - }], - }; - assert_eq!( - serde_json::to_value(&capabilities).unwrap()["capabilities"][0]["toolkit"], - "gmail" - ); - - let connections: ComposioConnectionsResponse = serde_json::from_value(json!({ - "connections": [ - { "id": "c1", "toolkit": " Gmail ", "status": " connected ", "createdAt": "2026-05-29T00:00:00Z" }, - { "id": "c2", "toolkit": "slack", "status": "PENDING" } - ] - })) - .unwrap(); - assert_eq!(connections.connections[0].normalized_toolkit(), "gmail"); - assert!(connections.connections[0].is_active()); - assert!(!connections.connections[1].is_active()); - let serialized_connection = serde_json::to_value(&connections.connections[0]).unwrap(); - assert_eq!(serialized_connection["createdAt"], "2026-05-29T00:00:00Z"); - - let default_connection = ComposioConnection { - id: "c3".into(), - toolkit: "notion".into(), - status: "FAILED".into(), - created_at: None, - account_email: None, - workspace: None, - username: None, - }; - assert!(serde_json::to_value(default_connection) - .unwrap() - .get("createdAt") - .is_none()); - - let tools = ComposioToolsResponse { - tools: vec![ComposioToolSchema { - kind: "function".into(), - function: ComposioToolFunction { - name: "GMAIL_SEND_EMAIL".into(), - description: Some("Send mail".into()), - parameters: Some(json!({ "type": "object" })), - output_parameters: None, - }, - }], - }; - assert_eq!( - serde_json::to_value(&tools).unwrap()["tools"][0]["type"], - "function" - ); - let default_kind: ComposioToolSchema = serde_json::from_value(json!({ - "function": { "name": "SLACK_SENDS_A_MESSAGE_TO_A_SLACK_CHANNEL" } - })) - .unwrap(); - assert_eq!(default_kind.kind, "function"); - assert_eq!(default_kind.function.description, None); - - let execute: ComposioExecuteResponse = serde_json::from_value(json!({ - "data": { "id": "msg-1" }, - "successful": true, - "costUsd": 0.03, - "markdownFormatted": "**sent**" - })) - .unwrap(); - assert!(execute.successful); - assert_eq!(execute.cost_usd, 0.03); - assert_eq!(execute.markdown_formatted.as_deref(), Some("**sent**")); - - let repos = ComposioGithubReposResponse { - connection_id: "conn-github".into(), - repositories: vec![ComposioGithubRepo { - owner: "tinyhumansai".into(), - repo: "openhuman".into(), - full_name: "tinyhumansai/openhuman".into(), - private: Some(false), - default_branch: Some("main".into()), - html_url: Some("https://github.com/tinyhumansai/openhuman".into()), - }], - }; - assert_eq!( - serde_json::to_value(&repos).unwrap()["connectionId"], - "conn-github" - ); - - let create = ComposioCreateTriggerResponse { - trigger_id: "trig-1".into(), - status: Some("enabled".into()), - }; - assert_eq!( - serde_json::to_value(&create).unwrap()["triggerId"], - "trig-1" - ); - let available = ComposioAvailableTriggersResponse { - triggers: vec![ComposioAvailableTrigger { - slug: "GITHUB_PULL_REQUEST_EVENT".into(), - scope: "github_repo".into(), - default_config: Some(json!({ "event": "pull_request" })), - required_config_keys: Some(vec!["owner".into(), "repo".into()]), - repo: Some(ComposioAvailableTriggerRepo { - owner: "tinyhumansai".into(), - repo: "openhuman".into(), - }), - }], - }; - assert_eq!( - serde_json::to_value(&available).unwrap()["triggers"][0]["repo"]["repo"], - "openhuman" - ); - - let active: ComposioActiveTriggersResponse = serde_json::from_value(json!({ - "triggers": [{ - "id": { "id": "trigger-id" }, - "slug": { "slug": "GMAIL_NEW_GMAIL_MESSAGE" }, - "toolkit": { "name": "gmail" }, - "connectionId": { "key": "conn-1" }, - "triggerConfig": { "label": "INBOX" }, - "state": { "state": "enabled" } - }] - })) - .unwrap(); - let active_trigger: &ComposioActiveTrigger = &active.triggers[0]; - assert_eq!(active_trigger.id, "trigger-id"); - assert_eq!(active_trigger.slug, "GMAIL_NEW_GMAIL_MESSAGE"); - assert_eq!(active_trigger.toolkit, "gmail"); - assert_eq!(active_trigger.connection_id, "conn-1"); - assert_eq!(active_trigger.state.as_deref(), Some("enabled")); - let active_without_state: ComposioActiveTrigger = serde_json::from_value(json!({ - "id": "trigger-2", - "slug": "SLACK_NEW_MESSAGE", - "toolkit": "slack", - "connectionId": "conn-2", - "state": { "unexpected": true } - })) - .unwrap(); - assert_eq!(active_without_state.state, None); - let active_string_state: ComposioActiveTrigger = serde_json::from_value(json!({ - "id": "trigger-2b", - "slug": "SLACK_NEW_MESSAGE", - "toolkit": "slack", - "connectionId": "conn-2", - "state": "READY" - })) - .unwrap(); - assert_eq!(active_string_state.state.as_deref(), Some("READY")); - let active_null_state: ComposioActiveTrigger = serde_json::from_value(json!({ - "id": "trigger-2c", - "slug": "SLACK_NEW_MESSAGE", - "toolkit": "slack", - "connectionId": "conn-2", - "state": null - })) - .unwrap(); - assert_eq!(active_null_state.state, None); - let active_numeric_state: ComposioActiveTrigger = serde_json::from_value(json!({ - "id": "trigger-2d", - "slug": "SLACK_NEW_MESSAGE", - "toolkit": "slack", - "connectionId": "conn-2", - "state": 12 - })) - .unwrap(); - assert_eq!(active_numeric_state.state, None); - assert!(serde_json::from_value::(json!({ - "id": ["bad"], - "slug": "x", - "toolkit": "gmail", - "connectionId": "c" - })) - .is_err()); - for bad_id in [json!(null), json!(true), json!(123)] { - assert!(serde_json::from_value::(json!({ - "id": bad_id, - "slug": "x", - "toolkit": "gmail", - "connectionId": "c" - })) - .is_err()); - } - let missing_nested_slug = serde_json::from_value::(json!({ - "id": "trigger-3", - "slug": { "unexpected": true }, - "toolkit": "gmail", - "connectionId": "c" - })) - .expect_err("nested slug object needs a known string key"); - assert!(missing_nested_slug.to_string().contains("slug/id/name/key")); - - let enable = ComposioEnableTriggerResponse { - trigger_id: "trig-2".into(), - slug: "SLACK_NEW_MESSAGE".into(), - connection_id: "conn-2".into(), - }; - assert_eq!( - serde_json::to_value(&enable).unwrap()["connectionId"], - "conn-2" - ); - assert!( - serde_json::to_value(ComposioDisableTriggerResponse { deleted: false }) - .unwrap() - .get("deleted") - .is_some() - ); - assert_eq!( - serde_json::to_value(ComposioDeleteResponse { - deleted: true, - memory_chunks_deleted: 4, - }) - .unwrap()["memory_chunks_deleted"], - 4 - ); - - let event: ComposioTriggerEvent = serde_json::from_value(json!({ - "toolkit": "gmail", - "trigger": "GMAIL_NEW_GMAIL_MESSAGE", - "payload": { "subject": "coverage" }, - "metadata": { "id": "m1", "uuid": "u1" } - })) - .unwrap(); - assert_eq!(event.metadata.id, "m1"); - assert_eq!(event.payload["subject"], "coverage"); - let default_event: ComposioTriggerEvent = serde_json::from_value(json!({})).unwrap(); - assert_eq!(default_event.metadata.uuid, ""); - let metadata = ComposioTriggerMetadata { - id: "m2".into(), - uuid: "u2".into(), - }; - assert_eq!(serde_json::to_value(metadata).unwrap()["uuid"], "u2"); - let entry = ComposioTriggerHistoryEntry { - received_at_ms: 42, - toolkit: "gmail".into(), - trigger: "GMAIL_NEW_GMAIL_MESSAGE".into(), - metadata_id: "m1".into(), - metadata_uuid: "u1".into(), - payload: json!({ "subject": "coverage" }), - }; - assert_eq!(serde_json::to_value(entry).unwrap()["received_at_ms"], 42); - let history = ComposioTriggerHistoryResult { - archive_dir: "/tmp/archive".into(), - current_day_file: "/tmp/archive/2026-05-29.jsonl".into(), - entries: vec![ComposioTriggerHistoryEntry { - received_at_ms: 43, - toolkit: "slack".into(), - trigger: "SLACK_NEW_MESSAGE".into(), - metadata_id: "m2".into(), - metadata_uuid: "u2".into(), - payload: json!({ "text": "coverage" }), - }], - }; - let history_json = serde_json::to_value(history).unwrap(); - assert_eq!(history_json["entries"][0]["metadata_uuid"], "u2"); -} - -#[test] -fn composio_direct_public_types_deserialize_polymorphic_toolkits() { - crate::tinyhumans_boot::boot(); - let plain: ComposioConnectedAccount = serde_json::from_value(json!({ - "id": "acct-1", - "status": "ACTIVE", - "createdAt": "2026-05-29T00:00:00Z", - "toolkit": " gmail " - })) - .unwrap(); - assert_eq!(plain.toolkit_slug().as_deref(), Some("gmail")); - assert_eq!(plain.created_at.as_deref(), Some("2026-05-29T00:00:00Z")); - - let nested: ComposioConnectedAccount = serde_json::from_value(json!({ - "id": "acct-2", - "toolkit": { "key": "slack" } - })) - .unwrap(); - assert_eq!(nested.toolkit_slug().as_deref(), Some("slack")); - - for (field, expected) in [ - ("slug", "github"), - ("id", "googlecalendar"), - ("name", "googledrive"), - ] { - let account: ComposioConnectedAccount = serde_json::from_value(json!({ - "id": format!("acct-{field}"), - "toolkit": { field: format!(" {expected} ") } - })) - .unwrap(); - assert_eq!(account.toolkit_slug().as_deref(), Some(expected)); - } - - let fallback: ComposioConnectedAccount = serde_json::from_value(json!({ - "id": "acct-3", - "toolkit": { "ignored": "value" }, - "app_name": " notion " - })) - .unwrap(); - assert_eq!(fallback.toolkit_slug().as_deref(), Some("notion")); - - let missing: ComposioConnectedAccount = serde_json::from_value(json!({ - "id": "acct-4", - "toolkit": ["bad"], - "appName": " " - })) - .unwrap(); - assert_eq!(missing.toolkit_slug(), None); -} - -async fn start_composio_round8_backend(app: Router) -> String { - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("bind mock composio backend"); - let addr = listener.local_addr().expect("mock backend addr"); - tokio::spawn(async move { - let _ = axum::serve(listener, app).await; - }); - format!("http://127.0.0.1:{}", addr.port()) -} - -fn store_app_session_token(config: &Config, token: &str) { - AuthService::from_config(config) - .store_provider_token( - APP_SESSION_PROVIDER, - DEFAULT_AUTH_PROFILE_NAME, - token, - std::collections::HashMap::new(), - true, - ) - .expect("store app session token"); -} - -async fn composio_round8_backend_handler(request: Request) -> Response { - let method = request.method().clone(); - let uri = request.uri().clone(); - let path = uri.path().to_string(); - let query = uri.query().unwrap_or_default().to_string(); - let body = to_bytes(request.into_body(), usize::MAX) - .await - .expect("mock request body"); - let body: Value = if body.is_empty() { - json!({}) - } else { - serde_json::from_slice(&body).expect("json request body") - }; - - match (method, path.as_str()) { - (Method::GET, "/agent-integrations/composio/toolkits") => ok(json!({ - "toolkits": ["gmail", "github", "slack"] - })), - (Method::GET, "/agent-integrations/composio/connections") => ok(json!({ - "connections": [ - { "id": "conn-gmail", "toolkit": " Gmail ", "status": "ACTIVE", "createdAt": "2026-05-29T00:00:00Z" }, - { "id": "conn-slack", "toolkit": "slack", "status": "PENDING" } - ] - })), - (Method::POST, "/agent-integrations/composio/authorize") => { - let toolkit = body - .get("toolkit") - .and_then(Value::as_str) - .expect("authorize toolkit"); - assert_eq!(toolkit.to_ascii_lowercase(), "gmail"); - let scopes = body - .get("oauth_scopes") - .and_then(Value::as_array) - .expect("oauth scopes array"); - assert!(scopes - .iter() - .any(|scope| scope == "https://www.googleapis.com/auth/gmail.readonly")); - ok(json!({ - "connectUrl": "https://connect.example/gmail", - "connectionId": "conn-gmail" - })) - } - (Method::GET, "/agent-integrations/composio/tools") => { - if !query.is_empty() { - assert!(query.contains("toolkits=gmail,github%2Frepo")); - assert!(query.contains("tags=important%20tag")); - } - ok(json!({ - "tools": [{ - "type": "function", - "function": { - "name": "GMAIL_SEND_EMAIL", - "description": "Send mail", - "parameters": { "type": "object" } - } - }] - })) - } - (Method::POST, "/agent-integrations/composio/execute") => { - match body.get("tool").and_then(Value::as_str) { - Some("GMAIL_FETCH_EMAILS") => ok(json!({ - "data": null, - "successful": false, - "error": "403 insufficient authentication scopes", - "costUsd": 0.0 - })), - _ => ok(json!({ - "data": { "id": "msg-1" }, - "successful": true, - "error": null, - "costUsd": 0.01, - "markdownFormatted": "**sent**" - })), - } - } - (Method::GET, "/agent-integrations/composio/github/repos") => ok(json!({ - "connectionId": "conn-github", - "repositories": [{ - "owner": "tinyhumansai", - "repo": "openhuman", - "fullName": "tinyhumansai/openhuman", - "private": false, - "defaultBranch": "main", - "htmlUrl": "https://github.com/tinyhumansai/openhuman" - }] - })), - (Method::POST, "/agent-integrations/composio/triggers") => { - if body.get("slug").and_then(Value::as_str) == Some("GITHUB_PULL_REQUEST_EVENT") { - assert_eq!(body["connectionId"], "conn-github"); - ok(json!({ - "triggerId": "created-trigger", - "status": "enabled" - })) - } else if body.get("connectionId").is_some() { - assert_eq!(body["connectionId"], "conn-gmail"); - ok(json!({ - "triggerId": "enabled-trigger", - "slug": "GMAIL_NEW_GMAIL_MESSAGE", - "connectionId": "conn-gmail" - })) - } else { - ok(json!({ - "triggerId": "created-trigger", - "status": "enabled" - })) - } - } - (Method::GET, "/agent-integrations/composio/triggers/available") => { - if query.contains("github") { - assert!(query.contains("connectionId=conn-github")); - ok(json!({ - "triggers": [{ - "slug": "GITHUB_PULL_REQUEST_EVENT", - "scope": "github_repo", - "defaultConfig": { "event": "pull_request" }, - "requiredConfigKeys": ["owner", "repo"], - "repo": { "owner": "tinyhumansai", "repo": "openhuman" } - }] - })) - } else { - ok(json!({ - "triggers": [{ - "slug": "GMAIL_NEW_GMAIL_MESSAGE", - "scope": "mailbox" - }] - })) - } - } - (Method::GET, "/agent-integrations/composio/triggers") => ok(json!({ - "triggers": [{ - "id": "active-trigger", - "slug": "GMAIL_NEW_GMAIL_MESSAGE", - "toolkit": "gmail", - "connectionId": "conn-gmail", - "triggerConfig": { "label": "INBOX" }, - "state": "enabled" - }] - })), - (Method::DELETE, path) if path.starts_with("/agent-integrations/composio/connections/") => { - let id = path.rsplit('/').next().unwrap_or_default(); - match id { - "bad-status" => ( - StatusCode::BAD_REQUEST, - Json(json!({ "success": false, "error": "delete rejected" })), - ) - .into_response(), - "bad-envelope" => Json(json!({ - "success": false, - "error": "delete envelope rejected" - })) - .into_response(), - _ => ok(json!({ "deleted": true, "memory_chunks_deleted": 2 })), - } - } - (Method::DELETE, path) if path.starts_with("/agent-integrations/composio/triggers/") => { - let id = path.rsplit('/').next().unwrap_or_default(); - if id == "no-data" { - Json(json!({ "success": true })).into_response() - } else { - ok(json!({ "deleted": true })) - } - } - _ => ( - StatusCode::NOT_FOUND, - Json(json!({ "success": false, "error": format!("unhandled {path}") })), - ) - .into_response(), - } -} - -fn ok(data: Value) -> Response { - Json(json!({ "success": true, "data": data })).into_response() -} diff --git a/tests/raw_coverage/composio_tools_direct_raw_coverage_e2e.rs b/tests/raw_coverage/composio_tools_direct_raw_coverage_e2e.rs index df9aa106aaf..8685f4fbec4 100644 --- a/tests/raw_coverage/composio_tools_direct_raw_coverage_e2e.rs +++ b/tests/raw_coverage/composio_tools_direct_raw_coverage_e2e.rs @@ -12,7 +12,6 @@ use axum::response::{IntoResponse, Response}; use axum::routing::any; use axum::{Json, Router}; use serde_json::{json, Value}; -use tempfile::tempdir; use openhuman_core::integrations::composio::client::direct_list_connections; use openhuman_core::tools::DirectComposioClient; diff --git a/tests/raw_coverage/connectivity_raw_coverage_e2e.rs b/tests/raw_coverage/connectivity_raw_coverage_e2e.rs index 273528a9d2c..8d3c8cacd0a 100644 --- a/tests/raw_coverage/connectivity_raw_coverage_e2e.rs +++ b/tests/raw_coverage/connectivity_raw_coverage_e2e.rs @@ -5,7 +5,7 @@ //! both through exported production APIs so the E2E lcov captures the real //! success and error branches. -use std::net::{SocketAddr, TcpListener as StdTcpListener}; +use std::net::SocketAddr; use std::path::Path; use std::sync::{Mutex, OnceLock}; @@ -15,15 +15,9 @@ use tempfile::{tempdir, TempDir}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR}; -use openhuman_core::platform::connectivity::ops::is_port_in_use; use openhuman_core::platform::connectivity::rpc::{ - diag, pick_listen_port, pick_listen_port_for_host, PickListenPortError, + pick_listen_port_for_host, PickListenPortError, }; -use openhuman_core::platform::connectivity::{ - all_connectivity_controller_schemas, all_connectivity_registered_controllers, - connectivity_controller_schema, -}; -use openhuman_core::platform::socket::{set_global_socket_manager, SocketManager}; use openhuman_rpc::server::build_core_http_router; const TEST_RPC_TOKEN: &str = "connectivity-raw-coverage-e2e-token"; @@ -203,53 +197,6 @@ fn payload<'a>(value: &'a Value, context: &str) -> &'a Value { .unwrap_or_else(|| panic!("{context} should include result.payload: {value}")) } -fn reserve_port() -> StdTcpListener { - StdTcpListener::bind("127.0.0.1:0").expect("reserve ephemeral port") -} - -fn reserve_contiguous_ports(count: usize) -> Option> { - const FIRST_CANDIDATE_PORT: u16 = 20_000; - const LAST_CANDIDATE_PORT: u16 = 60_000; - - for first in FIRST_CANDIDATE_PORT..=LAST_CANDIDATE_PORT { - let Some(last) = first.checked_add(count.saturating_sub(1) as u16) else { - break; - }; - if last > LAST_CANDIDATE_PORT { - break; - } - - let mut listeners = Vec::with_capacity(count); - let mut reserved = true; - for port in first..=last { - match StdTcpListener::bind(("127.0.0.1", port)) { - Ok(listener) => listeners.push(listener), - Err(_) => { - reserved = false; - break; - } - } - } - - if reserved { - return Some(listeners); - } - } - - None -} - -async fn spawn_probe_listener(status: &str, body: &'static str) -> ProbeListener { - spawn_probe_listener_on("127.0.0.1", status, body).await -} - -async fn spawn_probe_listener_on(host: &str, status: &str, body: &'static str) -> ProbeListener { - let listener = tokio::net::TcpListener::bind((host, 0)) - .await - .expect("bind probe listener"); - spawn_probe_listener_from(listener, status, body) -} - async fn try_spawn_probe_listener_on( host: &str, status: &str, @@ -335,245 +282,6 @@ async fn connectivity_diag_rpc_reports_live_listener_port_and_process() { harness.rpc_join.abort(); } -#[tokio::test] -async fn connectivity_diag_direct_path_prefers_rpc_url_and_handles_invalid_port_env() { - let _lock = env_lock(); - let _clean_rpc_url = EnvVarGuard::unset("OPENHUMAN_CORE_RPC_URL"); - let _clean_core_port = EnvVarGuard::unset("OPENHUMAN_CORE_PORT"); - let listener = reserve_port(); - let port = listener.local_addr().expect("reserved addr").port(); - let _rpc_url = EnvVarGuard::set( - "OPENHUMAN_CORE_RPC_URL", - &format!("http://127.0.0.1:{port}/rpc"), - ); - let _port_env = EnvVarGuard::set("OPENHUMAN_CORE_PORT", "not-a-port"); - - let outcome = diag().await.expect("diag should serialize"); - let value = outcome - .into_cli_compatible_json() - .expect("diag cli-compatible json"); - let diag_payload = value - .get("payload") - .or_else(|| value.get("result")) - .and_then(|p| p.get("diag")) - .unwrap_or_else(|| panic!("diag payload missing: {value}")); - - assert_eq!(diag_payload["listen_port"], json!(port)); - assert_eq!(diag_payload["listen_port_in_use"], json!(true)); - assert_eq!(diag_payload["last_ws_error"], Value::Null); - drop(listener); - - drop(_rpc_url); - let _invalid_port = EnvVarGuard::set("OPENHUMAN_CORE_PORT", "still-not-a-port"); - let fallback_default = diag() - .await - .expect("diag with invalid port env") - .into_cli_compatible_json() - .expect("invalid port diag json"); - assert_eq!( - fallback_default - .get("result") - .and_then(|p| p.get("diag")) - .and_then(|d| d.get("listen_port")), - Some(&json!(7788)) - ); - - drop(_invalid_port); - let _valid_port = EnvVarGuard::set("OPENHUMAN_CORE_PORT", &port.to_string()); - let env_port = diag() - .await - .expect("diag with valid port env") - .into_cli_compatible_json() - .expect("valid port diag json"); - assert_eq!( - env_port - .get("result") - .and_then(|p| p.get("diag")) - .and_then(|d| d.get("listen_port")), - Some(&json!(port)) - ); - - drop(_valid_port); - let _url_without_port = EnvVarGuard::set("OPENHUMAN_CORE_RPC_URL", "http://127.0.0.1/rpc"); - let _fallback_port = EnvVarGuard::set("OPENHUMAN_CORE_PORT", &port.to_string()); - let url_without_port = diag() - .await - .expect("diag should fall through URL without explicit port") - .into_cli_compatible_json() - .expect("url without port diag json"); - assert_eq!( - url_without_port - .get("result") - .and_then(|p| p.get("diag")) - .and_then(|d| d.get("listen_port")), - Some(&json!(port)) - ); -} - -#[tokio::test] -async fn connectivity_ops_schema_and_socket_snapshot_paths_are_exercised() { - let _lock = env_lock(); - let _clean_rpc_url = EnvVarGuard::unset("OPENHUMAN_CORE_RPC_URL"); - let _clean_core_port = EnvVarGuard::unset("OPENHUMAN_CORE_PORT"); - let reserved = reserve_port(); - let port = reserved.local_addr().expect("reserved addr").port(); - assert!(is_port_in_use(port)); - drop(reserved); - assert!(!is_port_in_use(port)); - - let schemas = all_connectivity_controller_schemas(); - assert_eq!(schemas.len(), 1); - assert_eq!(schemas[0].namespace, "connectivity"); - assert_eq!(schemas[0].function, "diag"); - assert_eq!(schemas[0].outputs[0].name, "diag"); - - let unknown = connectivity_controller_schema("missing"); - assert_eq!(unknown.namespace, "connectivity"); - assert_eq!(unknown.function, "unknown"); - assert_eq!(unknown.outputs[0].name, "error"); - assert!(unknown.description.contains("Unknown connectivity")); - - set_global_socket_manager(std::sync::Arc::new(SocketManager::new())); - let _core_port = EnvVarGuard::set("OPENHUMAN_CORE_PORT", &port.to_string()); - let value = diag() - .await - .expect("diag with socket manager") - .into_cli_compatible_json() - .expect("socket manager diag json"); - assert_eq!( - value - .get("result") - .and_then(|p| p.get("diag")) - .and_then(|d| d.get("socket_state")), - Some(&json!("disconnected")) - ); - - let registered = all_connectivity_registered_controllers(); - assert_eq!(registered.len(), 1); - assert_eq!( - registered[0].rpc_method_name(), - "openhuman.connectivity_diag" - ); - let handled = (registered[0].handler)(serde_json::Map::new()) - .await - .expect("registered connectivity handler"); - assert_eq!( - handled - .get("result") - .and_then(|p| p.get("diag")) - .and_then(|d| d.get("listen_port")), - Some(&json!(port)) - ); -} - -#[tokio::test] -async fn pick_listen_port_covers_preferred_free_wrapper_retry_and_bind_failure() { - let _lock = env_lock(); - let reserved = reserve_port(); - let free_port = reserved.local_addr().expect("reserved addr").port(); - drop(reserved); - - let picked = pick_listen_port(free_port) - .await - .expect("preferred port should bind"); - assert_eq!(picked.port, free_port); - assert_eq!(picked.fallback_from, None); - drop(picked.listener); - - let transient_listener = StdTcpListener::bind("127.0.0.1:0").expect("bind transient port"); - let transient_port = transient_listener - .local_addr() - .expect("transient addr") - .port(); - let release = tokio::task::spawn_blocking(move || { - std::thread::sleep(std::time::Duration::from_millis(650)); - drop(transient_listener); - }); - let picked = pick_listen_port_for_host("127.0.0.1", transient_port) - .await - .expect("preferred port should bind after transient release"); - assert_eq!(picked.port, transient_port); - assert_eq!(picked.fallback_from, None); - drop(picked.listener); - release.await.expect("release task ok"); - - let err = pick_listen_port_for_host("192.0.2.1", 7788) - .await - .expect_err("non-local bind should fail"); - assert!( - matches!(err, PickListenPortError::BindFailed { .. }), - "expected bind failure, got {err:?}" - ); - assert!(err - .to_string() - .contains("failed to bind core listener on port")); -} - -#[tokio::test] -async fn pick_listen_port_detects_openhuman_listener_for_takeover() { - let _lock = env_lock(); - let probe = spawn_probe_listener("200 OK", r#"{"name":"openhuman","ok":true}"#).await; - - let err = pick_listen_port_for_host("127.0.0.1", probe.port) - .await - .expect_err("openhuman listener should request takeover"); - assert!(err.to_string().contains("stale-listener takeover required")); - match err { - PickListenPortError::WouldTakeOver { - preferred, - fingerprint, - } => { - assert_eq!(preferred, probe.port); - assert_eq!(fingerprint, "openhuman-core"); - } - other => panic!("expected takeover error, got {other:?}"), - } -} - -#[tokio::test] -async fn pick_listen_port_falls_back_for_non_openhuman_and_status_fingerprints() { - let _lock = env_lock(); - let probe = spawn_probe_listener("200 OK", r#"{"name":"not-openhuman"}"#).await; - - let picked = pick_listen_port_for_host("127.0.0.1", probe.port) - .await - .expect("non-openhuman listener should fall back"); - assert!( - picked.port > probe.port, - "fallback port must be higher than probe port" - ); - assert_eq!(picked.fallback_from, Some(probe.port)); - drop(picked.listener); - drop(probe); - - let status_probe = spawn_probe_listener("503 Service Unavailable", r#"unavailable"#).await; - let picked = pick_listen_port_for_host("127.0.0.1", status_probe.port) - .await - .expect("non-success probe should fall back"); - assert!( - picked.port > status_probe.port, - "fallback port must be higher than status probe port" - ); - assert_eq!(picked.fallback_from, Some(status_probe.port)); - drop(picked.listener); - - let invalid_body_probe = spawn_probe_listener_on("0.0.0.0", "200 OK", "not json").await; - let picked = pick_listen_port_for_host("0.0.0.0", invalid_body_probe.port) - .await - .expect("invalid root JSON should fall back"); - assert_eq!(picked.fallback_from, Some(invalid_body_probe.port)); - drop(picked.listener); - - let raw_listener = StdTcpListener::bind("127.0.0.1:0").expect("bind raw listener"); - let raw_port = raw_listener.local_addr().expect("raw listener addr").port(); - let picked = pick_listen_port_for_host("127.0.0.1", raw_port) - .await - .expect("raw TCP listener should be classified as other and fall back"); - assert_eq!(picked.fallback_from, Some(raw_port)); - drop(picked.listener); - drop(raw_listener); -} - #[tokio::test] async fn pick_listen_port_identifies_ipv6_openhuman_listener_when_supported() { let _lock = env_lock(); @@ -599,47 +307,3 @@ async fn pick_listen_port_identifies_ipv6_openhuman_listener_when_supported() { } } -#[tokio::test] -async fn pick_listen_port_reports_no_available_fallbacks() { - let _lock = env_lock(); - let mut reserved = - reserve_contiguous_ports(11).expect("reserve preferred port and ten fallback ports"); - let preferred_std = reserved.remove(0); - preferred_std - .set_nonblocking(true) - .expect("mark preferred probe listener nonblocking"); - let preferred_listener = - tokio::net::TcpListener::from_std(preferred_std).expect("convert preferred probe listener"); - let preferred_probe = - spawn_probe_listener_from(preferred_listener, "200 OK", r#"{"name":"not-openhuman"}"#); - let preferred = preferred_probe.port; - let occupied = reserved; - - let err = pick_listen_port_for_host("127.0.0.1", preferred) - .await - .expect_err("all fallback ports should be exhausted"); - assert!( - err.to_string().contains("no fallback ports available"), - "display should include fallback exhaustion detail: {err}" - ); - match err { - PickListenPortError::NoAvailablePort { - preferred: actual_preferred, - fingerprint, - attempted, - } => { - assert_eq!(actual_preferred, preferred); - assert!( - fingerprint.contains("did not identify as openhuman"), - "unexpected fingerprint: {fingerprint}" - ); - assert_eq!( - attempted, - ((preferred + 1)..=(preferred + 10)).collect::>() - ); - } - other => panic!("expected no available port error, got {other:?}"), - } - - drop(occupied); -} diff --git a/tests/raw_coverage/flows_lifecycle_e2e.rs b/tests/raw_coverage/flows_lifecycle_e2e.rs index fc18c378abc..e6757ecd70d 100644 --- a/tests/raw_coverage/flows_lifecycle_e2e.rs +++ b/tests/raw_coverage/flows_lifecycle_e2e.rs @@ -429,321 +429,10 @@ async fn flows_draft_surface_round_trips_and_promotes_into_a_saved_flow() { h.join.abort(); } -/// A draft that names a `flow_id` must UPDATE that flow on promote rather than -/// create a second one — the behaviour `parse_draft_update_flow_id` exists to -/// protect. -#[tokio::test] -async fn flows_draft_promote_updates_the_linked_flow_instead_of_creating_a_second() { - let _lock = env_lock(); - let h = setup().await; - - let flow = h - .ok( - 1101, - "openhuman.flows_create", - json!({ "name": "Original", "graph": trigger_only_graph() }), - ) - .await; - let flow_id = str_at(&flow, "/id").to_string(); - - let draft = h - .ok( - 1102, - "openhuman.flows_draft_create", - json!({ - "name": "Edited In Canvas", - "graph": two_node_graph(), - "flow_id": flow_id, - }), - ) - .await; - assert_eq!( - draft.get("flow_id").and_then(Value::as_str), - Some(flow_id.as_str()), - "the draft records the flow it edits: {draft}" - ); - - let promoted = h - .ok( - 1103, - "openhuman.flows_draft_promote", - json!({ "id": str_at(&draft, "/id") }), - ) - .await; - assert_eq!( - str_at(&promoted, "/id"), - flow_id, - "promoting a linked draft updates the SAME flow: {promoted}" - ); - assert_eq!(str_at(&promoted, "/name"), "Edited In Canvas"); - - let flows = h.ok(1104, "openhuman.flows_list", json!({})).await; - assert_eq!( - flows.as_array().map(Vec::len), - Some(1), - "no second flow was created: {flows}" - ); - - h.join.abort(); -} - // ── duplicate / set_enabled ───────────────────────────────────────────────── -/// A duplicate is a copy that is deliberately born DISABLED and unbound, so it -/// can never fire on its own schedule before the user has reviewed it. -#[tokio::test] -async fn flows_duplicate_copies_the_graph_and_lands_disabled() { - let _lock = env_lock(); - let h = setup().await; - - let source = h - .ok( - 1201, - "openhuman.flows_create", - json!({ "name": "Nightly Report", "graph": two_node_graph() }), - ) - .await; - let source_id = str_at(&source, "/id").to_string(); - assert_eq!( - source.get("enabled").and_then(Value::as_bool), - Some(true), - "a manually triggered flow is created enabled" - ); - - let copy = h - .ok( - 1202, - "openhuman.flows_duplicate", - json!({ "id": source_id }), - ) - .await; - assert_ne!(str_at(©, "/id"), source_id, "the copy gets a fresh id"); - assert_eq!( - str_at(©, "/name"), - "Nightly Report (copy)", - "the copy is suffixed: {copy}" - ); - assert_eq!( - copy.get("enabled").and_then(Value::as_bool), - Some(false), - "a duplicate is born disabled: {copy}" - ); - assert_eq!( - copy.pointer("/graph/nodes") - .and_then(Value::as_array) - .map(Vec::len), - Some(2), - "the copy carries the source graph: {copy}" - ); - - let flows = h.ok(1203, "openhuman.flows_list", json!({})).await; - assert_eq!(flows.as_array().map(Vec::len), Some(2)); - - let missing = h - .err( - 1204, - "openhuman.flows_duplicate", - json!({ "id": "no-such-flow" }), - ) - .await; - assert!( - missing.contains("no-such-flow") && missing.contains("not found"), - "duplicate names the absent flow: {missing}" - ); - - h.join.abort(); -} - -/// `set_enabled` is the toggle behind the flow list's switch. Both directions -/// must be reflected in the stored flow, and a re-read must agree. -#[tokio::test] -async fn flows_set_enabled_toggles_both_ways_and_persists() { - let _lock = env_lock(); - let h = setup().await; - - let flow = h - .ok( - 1301, - "openhuman.flows_create", - json!({ "name": "Toggle Me", "graph": trigger_only_graph() }), - ) - .await; - let flow_id = str_at(&flow, "/id").to_string(); - - let off = h - .ok( - 1302, - "openhuman.flows_set_enabled", - json!({ "id": flow_id, "enabled": false }), - ) - .await; - assert_eq!(off.get("enabled").and_then(Value::as_bool), Some(false)); - - let reread = h - .ok(1303, "openhuman.flows_get", json!({ "id": flow_id })) - .await; - assert_eq!( - reread.get("enabled").and_then(Value::as_bool), - Some(false), - "the disable is persisted, not just echoed: {reread}" - ); - - let on = h - .ok( - 1304, - "openhuman.flows_set_enabled", - json!({ "id": flow_id, "enabled": true }), - ) - .await; - assert_eq!(on.get("enabled").and_then(Value::as_bool), Some(true)); - - let missing = h - .err( - 1305, - "openhuman.flows_set_enabled", - json!({ "id": "no-such-flow", "enabled": true }), - ) - .await; - assert!( - missing.to_lowercase().contains("not found") || missing.contains("no-such-flow"), - "set_enabled on an absent flow is an error: {missing}" - ); - - let no_flag = h - .err( - 1306, - "openhuman.flows_set_enabled", - json!({ "id": flow_id }), - ) - .await; - assert!( - no_flag.contains("enabled"), - "the required `enabled` param is named: {no_flag}" - ); - - h.join.abort(); -} - // ── history / rollback ────────────────────────────────────────────────────── -/// Every update snapshots the *prior* graph, and rollback restores one through -/// the normal update path — so the rollback is itself snapshotted and undoable. -#[tokio::test] -async fn flows_history_records_prior_graphs_and_rollback_restores_them() { - let _lock = env_lock(); - let h = setup().await; - - let flow = h - .ok( - 1401, - "openhuman.flows_create", - json!({ "name": "Versioned", "graph": trigger_only_graph() }), - ) - .await; - let flow_id = str_at(&flow, "/id").to_string(); - - let empty = h - .ok( - 1402, - "openhuman.flows_get_history", - json!({ "id": flow_id }), - ) - .await; - assert_eq!( - empty.as_array().map(Vec::len), - Some(0), - "a freshly created flow has no prior revisions: {empty}" - ); - - h.ok( - 1403, - "openhuman.flows_update", - json!({ "id": flow_id, "graph": two_node_graph() }), - ) - .await; - - let history = h - .ok( - 1404, - "openhuman.flows_get_history", - json!({ "id": flow_id }), - ) - .await; - let revisions = history.as_array().expect("get_history returns an array"); - assert_eq!(revisions.len(), 1, "one prior snapshot: {history}"); - let revision = &revisions[0]; - let revision_id = str_at(revision, "/id").to_string(); - assert_eq!( - revision.get("flow_id").and_then(Value::as_str), - Some(flow_id.as_str()) - ); - assert_eq!( - revision - .pointer("/graph/nodes") - .and_then(Value::as_array) - .map(Vec::len), - Some(1), - "the snapshot holds the ORIGINAL one-node graph, not the new one: {revision}" - ); - - let rolled = h - .ok( - 1405, - "openhuman.flows_rollback", - json!({ "id": flow_id, "revision_id": revision_id }), - ) - .await; - assert_eq!( - rolled - .pointer("/graph/nodes") - .and_then(Value::as_array) - .map(Vec::len), - Some(1), - "rollback restored the one-node graph: {rolled}" - ); - - let after = h - .ok( - 1406, - "openhuman.flows_get_history", - json!({ "id": flow_id }), - ) - .await; - assert_eq!( - after.as_array().map(Vec::len), - Some(2), - "the rollback snapshotted the graph it replaced, so it is undoable: {after}" - ); - - let bad_revision = h - .err( - 1407, - "openhuman.flows_rollback", - json!({ "id": flow_id, "revision_id": "no-such-revision" }), - ) - .await; - assert!( - bad_revision.contains("no-such-revision") && bad_revision.contains(&flow_id), - "rollback names both the revision and the flow: {bad_revision}" - ); - - // `limit` is honoured, not ignored. - let capped = h - .ok( - 1408, - "openhuman.flows_get_history", - json!({ "id": flow_id, "limit": 1 }), - ) - .await; - assert_eq!( - capped.as_array().map(Vec::len), - Some(1), - "get_history honours limit: {capped}" - ); - - h.join.abort(); -} - // ── run history: list_all_runs / prune_runs ───────────────────────────────── /// `flows_list_runs` is per-flow; `flows_list_all_runs` is the cross-flow feed @@ -841,238 +530,6 @@ async fn flows_list_all_runs_spans_flows_and_prune_reports_the_retention_cap() { // ── approval manifest / required connections ──────────────────────────────── -/// The save+enable pre-authorization card: one row per permission a run will -/// prompt for, classified, deduped on the trust key, and joined against the -/// grants the flow already holds. -#[tokio::test] -async fn flows_approval_manifest_classifies_every_gated_node_kind() { - let _lock = env_lock(); - let h = setup().await; - - let graph = json!({ - "nodes": [ - { "id": "t", "kind": "trigger", "name": "Manual" }, - { "id": "http", "kind": "http_request", "name": "Call", - "config": { "url": "https://example.invalid/hook", "method": "POST" } }, - { "id": "code", "kind": "code", "name": "Transform", - "config": { "language": "javascript", "code": "return items;" } }, - { "id": "dyn", "kind": "tool_call", "name": "Chosen at run time", - "config": { "slug": "=nodes.t.output.slug", "args": {} } }, - { "id": "ai", "kind": "agent", "name": "Summarize", - "config": { "agent_ref": "summarizer", "prompt": "summarize" } } - ], - "edges": [ - { "from_node": "t", "to_node": "http" }, - { "from_node": "http", "to_node": "code" }, - { "from_node": "code", "to_node": "dyn" }, - { "from_node": "dyn", "to_node": "ai" } - ] - }); - - let manifest = h - .ok( - 1601, - "openhuman.flows_approval_manifest", - json!({ "graph": graph }), - ) - .await; - let entries = manifest - .get("entries") - .and_then(Value::as_array) - .unwrap_or_else(|| panic!("manifest carries an entries array: {manifest}")); - - let find = |tool: &str| -> &Value { - entries - .iter() - .find(|entry| entry.get("tool_name").and_then(Value::as_str) == Some(tool)) - .unwrap_or_else(|| panic!("manifest must list {tool}: {manifest}")) - }; - - let http = find("flows_http_request"); - assert_eq!(http.get("node_id").and_then(Value::as_str), Some("http")); - assert_eq!(http.get("class").and_then(Value::as_str), Some("Network")); - assert_eq!( - str_at(http, "/label"), - "Call https://example.invalid/hook", - "the label names the destination so the card is readable: {http}" - ); - - let code = find("flows_code"); - assert_eq!(code.get("class").and_then(Value::as_str), Some("Write")); - - assert!( - entries.iter().any( - |entry| entry.get("kind").and_then(Value::as_str) == Some("dynamic") - && entry.get("node_id").and_then(Value::as_str) == Some("dyn") - ), - "an `=` slug cannot be pre-approved and must be disclosed as dynamic: {manifest}" - ); - assert!( - entries.iter().any( - |entry| entry.get("kind").and_then(Value::as_str) == Some("agent") - && entry.get("node_id").and_then(Value::as_str) == Some("ai") - ), - "an agent node's inner tool calls are unknowable and must be disclosed: {manifest}" - ); - - // `missing` and `already_trusted` partition the APPROVABLE keys — the - // dynamic and agent rows have no trust key to grant, so neither list may - // name them. - let gate_installed = manifest - .get("gate_installed") - .and_then(Value::as_bool) - .unwrap_or_else(|| panic!("gate_installed is reported as a boolean: {manifest}")); - let missing: Vec<&str> = manifest - .get("missing") - .and_then(Value::as_array) - .expect("missing array") - .iter() - .filter_map(Value::as_str) - .collect(); - let already: Vec<&str> = manifest - .get("already_trusted") - .and_then(Value::as_array) - .expect("already_trusted array") - .iter() - .filter_map(Value::as_str) - .collect(); - - if gate_installed { - // No `id` was given, so no grants can be joined: every approvable key - // is missing and nothing is already trusted. - assert!( - missing.contains(&"flows_http_request") && missing.contains(&"flows_code"), - "un-granted approvable keys are listed as missing: {missing:?}" - ); - assert!( - already.is_empty(), - "a candidate graph joined against no flow holds no grants: {already:?}" - ); - } else { - // Gate uninstalled: nothing ever parks, so nothing is `missing`; and no - // grant was ever made, so nothing is `already_trusted` either. - // `gate_installed: false` is the caller's only signal. - // - // This branch used to assert the opposite — the approvable keys landed - // in `already_trusted`, claiming grants the flow did not hold. openhuman#6093 - // fixed that (`split_manifest_trust` returns two empty lists when the - // gate is absent), so the assertion is inverted to the fixed behaviour. - assert!( - missing.is_empty(), - "with no gate installed nothing can park, so nothing is missing: {missing:?}" - ); - assert!( - already.is_empty(), - "with no gate installed no grant was ever made, so nothing is already \ - trusted either: {already:?}" - ); - } - for list in [&missing, &already] { - assert!( - !list.contains(&"dyn") && !list.contains(&"ai"), - "only approvable rows carry a trust key: {list:?}" - ); - } - - let neither = h - .err(1602, "openhuman.flows_approval_manifest", json!({})) - .await; - assert!( - neither.contains("'id'") && neither.contains("'graph'"), - "the manifest says which of the two inputs it needs: {neither}" - ); - - let unknown = h - .err( - 1603, - "openhuman.flows_approval_manifest", - json!({ "id": "no-such-flow" }), - ) - .await; - assert!( - unknown.contains("no-such-flow"), - "the manifest names the absent flow: {unknown}" - ); - - h.join.abort(); -} - -/// The "Connect " CTAs. Composio slugs contribute a toolkit; native -/// `oh:` tools and plain HTTP nodes deliberately do not. -#[tokio::test] -async fn flows_required_connections_lists_only_composio_toolkits() { - let _lock = env_lock(); - let h = setup().await; - - let graph = json!({ - "nodes": [ - { "id": "t", "kind": "trigger", "name": "Manual" }, - { "id": "send", "kind": "tool_call", "name": "Send", - "config": { "slug": "GMAIL_SEND_EMAIL", "args": {} } }, - { "id": "native", "kind": "tool_call", "name": "Native", - "config": { "slug": "oh:web_search", "args": {} } }, - { "id": "http", "kind": "http_request", "name": "Webhook", - "config": { "url": "https://example.invalid/hook", "method": "POST" } } - ], - "edges": [ - { "from_node": "t", "to_node": "send" }, - { "from_node": "send", "to_node": "native" }, - { "from_node": "native", "to_node": "http" } - ] - }); - - let out = h - .ok( - 1701, - "openhuman.flows_required_connections", - json!({ "graph": graph }), - ) - .await; - let required = out - .get("required_connections") - .and_then(Value::as_array) - .unwrap_or_else(|| panic!("required_connections array: {out}")); - assert_eq!( - required.len(), - 1, - "only the Composio slug needs a connection — `oh:` and http_request do not: {out}" - ); - assert_eq!( - required[0].get("toolkit").and_then(Value::as_str), - Some("gmail") - ); - assert_eq!( - required[0].get("status").and_then(Value::as_str), - Some("missing"), - "a fresh workspace has no Gmail connection: {out}" - ); - - let none = h - .ok( - 1702, - "openhuman.flows_required_connections", - json!({ "graph": trigger_only_graph() }), - ) - .await; - assert_eq!( - none.get("required_connections") - .and_then(Value::as_array) - .map(Vec::len), - Some(0), - "a trigger-only graph needs no connection: {none}" - ); - - let no_graph = h - .err(1703, "openhuman.flows_required_connections", json!({})) - .await; - assert!( - no_graph.contains("graph"), - "the required `graph` param is named: {no_graph}" - ); - - h.join.abort(); -} - // ── canvas tool browser ───────────────────────────────────────────────────── /// The in-canvas tool browser reads the LIVE Composio catalog. With no diff --git a/tests/raw_coverage/inference_local_admin_raw_coverage_e2e.rs b/tests/raw_coverage/inference_local_admin_raw_coverage_e2e.rs index dc82fa5c694..8aa9df29c42 100644 --- a/tests/raw_coverage/inference_local_admin_raw_coverage_e2e.rs +++ b/tests/raw_coverage/inference_local_admin_raw_coverage_e2e.rs @@ -3,7 +3,6 @@ //! This suite uses temp workspaces, temp PATH scripts, and loopback HTTP mocks //! only. It must not call host Ollama, Piper, Whisper, Python, or MLX binaries. -use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, MutexGuard, OnceLock}; @@ -16,18 +15,12 @@ use axum::{Json, Router}; use serde_json::{json, Value}; use tempfile::{tempdir, TempDir}; -use openhuman_core::config::schema::cloud_providers::{ - AuthStyle as CloudAuthStyle, CloudProviderCreds, -}; use openhuman_core::config::Config; -use openhuman_core::security::credentials::{AuthService, DEFAULT_AUTH_PROFILE_NAME}; use openhuman_core::inference::host_runtime::ops::{ local_ai_chat, local_ai_download_asset, local_ai_downloads_progress, LocalAiChatMessage, }; use openhuman_core::inference::host_runtime::LocalAiService; -use openhuman_core::inference::provider::factory::auth_key_for_slug; -use openhuman_core::inference::provider::list_configured_models; #[derive(Clone, Default)] struct MockState { @@ -218,144 +211,6 @@ async fn local_admin_covers_assets_diagnostics_downloads_and_ops_errors() { assert_eq!(ops_asset.embedding.state, "ready"); } -#[tokio::test] -async fn provider_model_listing_covers_local_synthesis_and_openrouter_failures() { - let _env_guard = env_lock(); - let (base, _state) = serve_mock().await; - let tmp = tempdir().expect("tempdir"); - let mut config = temp_config(&tmp); - config.local_ai.base_url = Some(base.clone()); - config.cloud_providers = vec![ - CloudProviderCreds { - id: "openrouter-id".to_string(), - slug: "openrouter".to_string(), - label: "OpenRouter".to_string(), - endpoint: format!("{base}/openrouter-error"), - auth_style: CloudAuthStyle::Bearer, - legacy_type: None, - default_model: None, - }, - CloudProviderCreds { - id: "array-id".to_string(), - slug: "array-body".to_string(), - label: "Array Body".to_string(), - endpoint: format!("{base}/array-body"), - auth_style: CloudAuthStyle::None, - legacy_type: None, - default_model: None, - }, - CloudProviderCreds { - id: "status-id".to_string(), - slug: "status-body".to_string(), - label: "Status Body".to_string(), - endpoint: format!("{base}/status-body"), - auth_style: CloudAuthStyle::None, - legacy_type: None, - default_model: None, - }, - ]; - config.save().await.expect("save config"); - AuthService::from_config(&config) - .store_provider_token( - &auth_key_for_slug("openrouter"), - DEFAULT_AUTH_PROFILE_NAME, - "sk-openrouter-secret", - HashMap::new(), - true, - ) - .expect("store token"); - - let _workspace = EnvVarGuard::set("OPENHUMAN_WORKSPACE", config.config_path.parent().unwrap()); - let _ollama_base = EnvVarGuard::set("OPENHUMAN_OLLAMA_BASE_URL", &base); - - let local = list_configured_models("ollama") - .await - .expect("synthetic ollama") - .value; - assert_eq!(local["models"][0]["id"], "bge-m3"); - - let array_err = list_configured_models("array-body") - .await - .expect_err("top-level array"); - assert!(array_err.contains("not a JSON object")); - - let status_err = list_configured_models("status-body") - .await - .expect_err("non-success"); - assert!(status_err.contains("provider returned 500")); - assert!(!status_err.contains("sk-status-secret")); - - let openrouter_err = list_configured_models("openrouter") - .await - .expect_err("openrouter key validation error payload"); - assert!(openrouter_err.contains("OpenRouter key validation returned error payload")); - assert!(!openrouter_err.contains("sk-openrouter-secret")); -} - -#[tokio::test] -async fn local_admin_reports_unhealthy_runtime_and_lm_studio_issue_shapes() { - let _env_guard = env_lock(); - let tmp = tempdir().expect("tempdir"); - let mut config = temp_config(&tmp); - config.local_ai.runtime_enabled = true; - config.local_ai.base_url = Some("http://127.0.0.1:9".to_string()); - let _ollama_base = EnvVarGuard::set("OPENHUMAN_OLLAMA_BASE_URL", "http://127.0.0.1:9"); - let runtime = openhuman_core::inference::local_runtime_config(&config); - let service = LocalAiService::new(&runtime); - - let unhealthy = service.diagnostics(&runtime).await.expect("unhealthy diag"); - assert_eq!(unhealthy["ollama_running"], false); - assert!(unhealthy["issues"][0] - .as_str() - .unwrap() - .contains("not running or not reachable")); - let assets = service - .assets_status(&runtime) - .await - .expect("unhealthy assets"); - assert!(!assets.ollama_available); - assert_eq!(assets.chat.state, "missing"); - - let (base, _state) = serve_mock().await; - let mut lm_config = config.clone(); - lm_config.local_ai.provider = "lm-studio".to_string(); - lm_config.local_ai.base_url = Some(format!("{base}/lm-empty/v1")); - lm_config.local_ai.chat_model_id = "loaded-chat".to_string(); - let mut lm_runtime = openhuman_core::inference::local_runtime_config(&lm_config); - let lm_empty = service - .diagnostics(&lm_runtime) - .await - .expect("lm studio empty"); - assert_eq!(lm_empty["provider"], "lm_studio"); - assert_eq!(lm_empty["lm_studio_running"], true); - assert!(lm_empty["issues"][0] - .as_str() - .unwrap() - .contains("no models are loaded")); - - lm_config.local_ai.base_url = Some(format!("{base}/lm-wrong/v1")); - lm_runtime = openhuman_core::inference::local_runtime_config(&lm_config); - let lm_wrong = service - .diagnostics(&lm_runtime) - .await - .expect("lm studio wrong model"); - assert!(lm_wrong["issues"][0] - .as_str() - .unwrap() - .contains("not loaded")); - - lm_config.local_ai.base_url = Some(format!("{base}/lm-error/v1")); - lm_runtime = openhuman_core::inference::local_runtime_config(&lm_config); - let lm_error = service - .diagnostics(&lm_runtime) - .await - .expect("lm studio error payload"); - assert!(lm_error["issues"][0] - .as_str() - .unwrap() - .contains("no models are loaded")); -} - async fn serve_mock() -> (String, MockState) { let state = MockState::default(); *state.ollama_models.lock().expect("models") = diff --git a/tests/raw_coverage/inference_local_ops_piper_raw_coverage_e2e.rs b/tests/raw_coverage/inference_local_ops_piper_raw_coverage_e2e.rs index e1c7f9e97d9..0e62b4e0e26 100644 --- a/tests/raw_coverage/inference_local_ops_piper_raw_coverage_e2e.rs +++ b/tests/raw_coverage/inference_local_ops_piper_raw_coverage_e2e.rs @@ -17,9 +17,7 @@ use flate2::write::GzEncoder; use flate2::Compression; use openhuman_core::core::all::RegisteredController; use openhuman_core::config::Config; -use openhuman_core::inference::host_runtime::{ - all_local_inference_registered_controllers, local_ai_transcribe_bytes, -}; +use openhuman_core::inference::host_runtime::all_local_inference_registered_controllers; use serde_json::{json, Value}; use tempfile::{tempdir, TempDir}; @@ -128,26 +126,6 @@ async fn piper_controller_rejects_insecure_download_overrides() { assert!(requests.is_empty(), "rejected URLs must not be requested"); } -#[tokio::test] -async fn local_transcribe_bytes_covers_temp_file_path_and_extension_validation() { - let tmp = tempdir().expect("tempdir"); - let mut config = temp_config(&tmp); - config.local_ai.runtime_enabled = false; - - let invalid = local_ai_transcribe_bytes(&config, b"audio", Some("../wav".to_string())) - .await - .expect_err("invalid extension"); - assert_eq!(invalid, "Invalid audio extension"); - - let disabled = local_ai_transcribe_bytes(&config, b"audio", Some(".WEBM".to_string())) - .await - .expect_err("hosted STT without a configured session"); - assert!( - !disabled.contains("local ai is disabled"), - "hosted STT must not be gated on the local-AI runtime: {disabled}" - ); -} - async fn serve_piper_mock() -> (String, PiperMockState) { let state = PiperMockState { requests: Arc::new(Mutex::new(Vec::new())), @@ -206,10 +184,6 @@ fn bytes_response(bytes: Vec) -> Response { .expect("response") } -fn set_mode(state: &PiperMockState, mode: PiperMockMode) { - *state.mode.lock().expect("mode") = mode; -} - fn valid_tar_gz_archive() -> Vec { let encoder = GzEncoder::new(Vec::new(), Compression::none()); let mut archive = tar::Builder::new(encoder); @@ -255,10 +229,6 @@ async fn wait_for_piper_state(status: &RegisteredController, wanted: &str) -> Va wait_for_piper(status, |value| value["state"] == wanted).await } -async fn wait_for_piper_stage(status: &RegisteredController, wanted: &str) -> Value { - wait_for_piper(status, |value| value["stage"] == wanted).await -} - async fn wait_for_piper(status: &RegisteredController, done: impl Fn(&Value) -> bool) -> Value { let deadline = Instant::now() + Duration::from_secs(20); let mut last = Value::Null; diff --git a/tests/raw_coverage/inference_local_services_round21_raw_coverage_e2e.rs b/tests/raw_coverage/inference_local_services_round21_raw_coverage_e2e.rs index 9b06b086fba..6afee018d74 100644 --- a/tests/raw_coverage/inference_local_services_round21_raw_coverage_e2e.rs +++ b/tests/raw_coverage/inference_local_services_round21_raw_coverage_e2e.rs @@ -5,7 +5,6 @@ use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, OnceLock}; -use std::time::{Duration, Instant}; use axum::body::Body; use axum::extract::State; @@ -13,16 +12,13 @@ use axum::http::{header, HeaderMap, Response, StatusCode}; use axum::response::IntoResponse; use axum::routing::{get, post}; use axum::{Json, Router}; -use openhuman_core::core::all::RegisteredController; use openhuman_core::config::Config; use openhuman_core::inference::host_runtime::ops::{ - local_ai_assets_status, local_ai_chat, local_ai_download_asset, local_ai_downloads_progress, - local_ai_prompt, local_ai_transcribe, local_ai_transcribe_bytes, + local_ai_chat, local_ai_download_asset, local_ai_downloads_progress, + local_ai_prompt, LocalAiChatMessage, }; -use openhuman_core::inference::host_runtime::{ - all_local_inference_registered_controllers, LocalAiService, -}; +use openhuman_core::inference::host_runtime::LocalAiService; use serde_json::{json, Value}; use tempfile::{tempdir, TempDir}; @@ -381,29 +377,6 @@ fn remember(state: &MockState, path: &str, _headers: &HeaderMap, body: Value) { .push((path.to_string(), body)); } -fn remember_path(state: &MockState, path: &str) { - state - .requests - .lock() - .expect("requests") - .push((path.to_string(), Value::Null)); -} - -fn controller<'a>( - controllers: &'a [RegisteredController], - function: &str, -) -> &'a RegisteredController { - controllers - .iter() - .find(|controller| controller.schema.function == function) - .unwrap_or_else(|| panic!("controller {function} registered")) -} - -async fn call(controller: &RegisteredController, params: Value) -> Result { - let params = params.as_object().cloned().unwrap_or_default(); - (controller.handler)(params).await -} - fn temp_config(tmp: &TempDir) -> Config { let root = tmp.path().join(".openhuman"); std::fs::create_dir_all(root.join("workspace")).expect("workspace dir"); diff --git a/tests/raw_coverage/inference_provider_admin_round22_raw_coverage_e2e.rs b/tests/raw_coverage/inference_provider_admin_round22_raw_coverage_e2e.rs index d2171546c04..45da2f28fdf 100644 --- a/tests/raw_coverage/inference_provider_admin_round22_raw_coverage_e2e.rs +++ b/tests/raw_coverage/inference_provider_admin_round22_raw_coverage_e2e.rs @@ -5,7 +5,6 @@ //! whisper, piper, local AI binaries, models, or downloads. use std::collections::HashMap; -use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, OnceLock}; use axum::extract::State; @@ -25,7 +24,6 @@ use openhuman_core::config::Config; use openhuman_core::security::credentials::{ AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME, }; -use openhuman_core::inference::host_runtime::LocalAiService; use openhuman_core::inference::provider::factory::{ auth_key_for_slug, create_chat_model_from_string_with_model_id, }; @@ -56,13 +54,6 @@ impl EnvVarGuard { unsafe { std::env::set_var(key, value) }; Self { key, previous } } - - fn unset(key: &'static str) -> Self { - let previous = std::env::var_os(key); - // SAFETY: this integration test is validated with --test-threads=1. - unsafe { std::env::remove_var(key) }; - Self { key, previous } - } } impl Drop for EnvVarGuard { @@ -286,82 +277,6 @@ async fn factory_covers_legacy_api_key_scoping_and_abstract_model_errors() { .is_some_and(|auth| auth.contains("sk-legacy-direct")))); } -#[tokio::test] -async fn local_admin_covers_diagnostics_errors_assets_status_and_shutdown_with_fake_bins() { - let _env = env_lock(); - let (base, _state) = serve_mock().await; - let tmp = tempdir().expect("tempdir"); - let mut config = temp_config(&tmp); - config.local_ai.runtime_enabled = true; - config.local_ai.opt_in_confirmed = true; - config.local_ai.base_url = Some(base.clone()); - config.local_ai.chat_model_id = "gemma3n:e4b-it-q8_0".to_string(); - config.local_ai.embedding_model_id = "all-minilm:latest".to_string(); - config.local_ai.selected_tier = Some("custom".to_string()); - config.local_ai.preload_embedding_model = true; - config.local_ai.preload_stt_model = true; - config.local_ai.preload_tts_voice = true; - config.local_ai.stt_model_id = "round22-stt".to_string(); - config.local_ai.tts_voice_id = "round22-voice".to_string(); - - let scripts = tempdir().expect("scripts"); - let ollama = write_stub_script(&scripts, "ollama", "#!/bin/sh\nprintf 'fake ollama\\n'\n"); - write_stub_script(&scripts, "python", "#!/bin/sh\nexit 42\n"); - write_stub_script(&scripts, "python3", "#!/bin/sh\nexit 42\n"); - write_stub_script(&scripts, "mlx_lm.generate", "#!/bin/sh\nexit 42\n"); - write_stub_script(&scripts, "piper", "#!/bin/sh\nexit 42\n"); - - let _path = EnvVarGuard::set("PATH", scripts.path()); - let _workspace = EnvVarGuard::set("OPENHUMAN_WORKSPACE", config.config_path.parent().unwrap()); - let _ollama_base = EnvVarGuard::set("OPENHUMAN_OLLAMA_BASE_URL", &base); - let _ollama_bin = EnvVarGuard::set("OLLAMA_BIN", &ollama); - let _piper_bin = EnvVarGuard::unset("PIPER_BIN"); - let _whisper_bin = EnvVarGuard::unset("WHISPER_BIN"); - - let runtime = openhuman_core::inference::local_runtime_config(&config); - let service = LocalAiService::new(&runtime); - let diag = service.diagnostics(&runtime).await.expect("diagnostics"); - assert_eq!(diag["ollama_running"], true); - let issues = diag["issues"].as_array().expect("issues"); - assert!(issues.iter().any(|issue| issue - .as_str() - .unwrap() - .contains("Chat model `gemma3n:e4b-it-q8_0`"))); - assert!(issues.iter().any(|issue| issue - .as_str() - .unwrap() - .contains("Embedding model `all-minilm:latest`"))); - - let mut tags_500 = config.clone(); - tags_500.local_ai.base_url = Some(format!("{base}/tags-500")); - let tags_500_runtime = openhuman_core::inference::local_runtime_config(&tags_500); - let diag_500 = service - .diagnostics(&tags_500_runtime) - .await - .expect("500 diagnostics"); - assert_eq!(diag_500["ollama_running"], false); - assert!(diag_500["issues"][0] - .as_str() - .unwrap() - .contains("not running or not reachable")); - - let assets = service.assets_status(&runtime).await.expect("assets status"); - assert!(assets.ollama_available); - assert_eq!(assets.chat.state, "missing"); - assert_eq!(assets.embedding.state, "missing"); - assert_ne!(assets.tts.state, "ready"); - - let child = tokio::process::Command::new("/bin/sh") - .arg("-c") - .arg("sleep 30") - .spawn() - .expect("spawn fake owned ollama child"); - service.inject_owned_ollama(child); - assert!(service.has_owned_ollama()); - service.shutdown_owned_ollama(&runtime).await; - assert!(!service.has_owned_ollama()); -} - async fn serve_mock() -> (String, MockState) { let state = MockState::default(); let app = Router::new() @@ -543,19 +458,3 @@ fn temp_config(tmp: &TempDir) -> Config { config } -fn write_stub_script(tmp: &TempDir, name: &str, body: &str) -> PathBuf { - let path = tmp.path().join(name); - std::fs::write(&path, body).expect("write stub"); - make_executable(&path); - path -} - -fn make_executable(path: &Path) { - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let mut perms = std::fs::metadata(path).expect("metadata").permissions(); - perms.set_mode(0o755); - std::fs::set_permissions(path, perms).expect("chmod"); - } -} diff --git a/tests/raw_coverage/inference_provider_raw_coverage_e2e.rs b/tests/raw_coverage/inference_provider_raw_coverage_e2e.rs index 8ac1387d229..55dd202a4e2 100644 --- a/tests/raw_coverage/inference_provider_raw_coverage_e2e.rs +++ b/tests/raw_coverage/inference_provider_raw_coverage_e2e.rs @@ -22,12 +22,10 @@ use openhuman_core::config::Config; use openhuman_core::security::credentials::{ AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME, }; -use openhuman_core::inference::host_runtime::LocalAiService; use openhuman_core::inference::provider::factory::{ auth_key_for_slug, create_chat_model_from_string_with_model_id, provider_for_role, }; use openhuman_core::inference::provider::list_configured_models; -use tinyinference_core::sanitize::sanitize_api_error; #[derive(Clone, Default)] struct MockState { @@ -203,12 +201,6 @@ async fn provider_factory_and_model_listing_cover_cloud_local_and_invalid_shapes assert_eq!(listed["models"][0]["id"], "demo-chat"); assert_eq!(listed["models"][1]["context_window"], 8192); - let local_listed = list_configured_models("ollama") - .await - .expect("synthetic ollama list") - .value; - assert_eq!(local_listed["models"][0]["id"], "demo-chat"); - // PR #2959 reverted the list_models 404 suppression: a 404 from /models // now surfaces as a real error instead of a synthetic `unsupported: true` // success, so the failure fires to Sentry for a root-cause fix. @@ -220,12 +212,6 @@ async fn provider_factory_and_model_listing_cover_cloud_local_and_invalid_shapes "404 list_models error should surface the status: {missing_err:?}" ); - let openrouter = list_configured_models("openrouter") - .await - .expect("openrouter key validation and list") - .value; - assert_eq!(openrouter["models"][0]["owned_by"], "test-suite"); - for provider_id in ["html", "wrong-data", "error-payload", ""] { let err = list_configured_models(provider_id) .await @@ -239,86 +225,6 @@ async fn provider_factory_and_model_listing_cover_cloud_local_and_invalid_shapes } } -#[tokio::test] -async fn local_service_public_inference_assets_and_shutdown_use_loopback_ollama() { - let _env_lock = __shared_env_lock(); - let (base, _state) = serve_mock().await; - let _ollama_env = EnvVarGuard::set("OPENHUMAN_OLLAMA_BASE_URL", &base); - let tmp = tempdir().expect("tempdir"); - let mut config = temp_config(&tmp); - config.local_ai.runtime_enabled = true; - config.local_ai.base_url = Some(base); - config.local_ai.chat_model_id = "gemma3:1b-it-qat".to_string(); - config.local_ai.vision_model_id = "llava:mock".to_string(); - config.local_ai.embedding_model_id = "bge-m3".to_string(); - config.local_ai.preload_embedding_model = true; - config.local_ai.preload_vision_model = false; - config.local_ai.preload_stt_model = false; - config.local_ai.preload_tts_voice = false; - - let runtime = openhuman_core::inference::local_runtime_config(&config); - let service = LocalAiService::new(&runtime); - let prompt = service - .prompt(&runtime, "Say hi", Some(8), true) - .await - .expect("prompt"); - assert_eq!(prompt, "chat:gemma3:1b-it-qat"); - - let summarized = service - .summarize(&runtime, "one two three", Some(16)) - .await - .expect("summarize"); - assert_eq!(summarized, "chat:gemma3:1b-it-qat"); - - let completion = service - .inline_complete_interactive( - &runtime, - "OpenHuman is", - "concise", - Some("short"), - &["OpenHuman is useful".to_string()], - Some(6), - ) - .await - .expect("inline"); - assert_eq!(completion, "chat:gemma3:1b-it-qat"); - - let assets = service.assets_status(&runtime).await.expect("assets"); - assert!(assets.ollama_available); - assert_eq!(assets.chat.state, "ready"); - assert_eq!(assets.embedding.state, "ready"); - assert!(matches!( - assets.tts.state.as_str(), - "ready" | "ondemand" | "missing" - )); - - let diagnostics = service.diagnostics(&runtime).await.expect("diagnostics"); - assert_eq!(diagnostics["ollama_running"], true); - assert_eq!(diagnostics["expected"]["chat_found"], true); - assert!( - diagnostics["installed_models"] - .as_array() - .expect("installed_models") - .len() - >= 4 - ); - - let progress = service.downloads_progress(&runtime).await.expect("progress"); - assert_eq!(progress.chat.id, "gemma3:1b-it-qat"); - assert_eq!(progress.embedding.id, "bge-m3"); - - let disabled_config = Config::default(); - let disabled_runtime = openhuman_core::inference::local_runtime_config(&disabled_config); - let disabled_err = service - .prompt(&disabled_runtime, "disabled", None, false) - .await - .expect_err("disabled prompt"); - assert_eq!(disabled_err, "local ai is disabled"); - - service.shutdown_owned_ollama(&runtime).await; - assert!(!service.has_owned_ollama()); -} - fn temp_config(tmp: &TempDir) -> Config { let root = tmp.path().join(".openhuman"); std::fs::create_dir_all(root.join("workspace")).expect("workspace dir"); diff --git a/tests/raw_coverage/inference_round26_raw_coverage_e2e.rs b/tests/raw_coverage/inference_round26_raw_coverage_e2e.rs deleted file mode 100644 index cf08298d8ff..00000000000 --- a/tests/raw_coverage/inference_round26_raw_coverage_e2e.rs +++ /dev/null @@ -1,400 +0,0 @@ -//! Round 26 raw/E2E coverage for high-yield inference cold paths. -//! -//! This suite uses loopback HTTP mocks and temporary fake executables only. It -//! must not call host Ollama, MLX, Python, whisper, piper, local AI binaries, -//! models, or downloads. - -use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex}; - -use axum::body::Body; -use axum::extract::State; -use axum::http::{header, HeaderMap, Response, StatusCode}; -use axum::response::IntoResponse; -use axum::routing::{get, post}; -use axum::{Json, Router}; -use openhuman_core::config::Config; -use openhuman_core::agent::messages::ChatMessage; -use openhuman_core::inference::host_runtime::LocalAiService; -use openhuman_core::inference::provider::types::{ChatRequest, ProviderDelta}; -use tinytools::ToolSpec; -use serde_json::{json, Value}; -use tempfile::{tempdir, TempDir}; - -#[derive(Clone, Default)] -struct MockState { - requests: Arc>>, - tool_retry_attempts: Arc>, -} - -#[derive(Clone, Debug)] -struct SeenRequest { - path: String, - auth: Option, - body: Value, -} - -struct EnvVarGuard { - key: &'static str, - previous: Option, -} - -impl EnvVarGuard { - fn set(key: &'static str, value: impl AsRef) -> Self { - let previous = std::env::var_os(key); - // SAFETY: validation runs this integration test with --test-threads=1. - unsafe { std::env::set_var(key, value) }; - Self { key, previous } - } - - fn unset(key: &'static str) -> Self { - let previous = std::env::var_os(key); - // SAFETY: validation runs this integration test with --test-threads=1. - unsafe { std::env::remove_var(key) }; - Self { key, previous } - } -} - -impl Drop for EnvVarGuard { - fn drop(&mut self) { - match &self.previous { - Some(value) => { - // SAFETY: validation runs this integration test with --test-threads=1. - unsafe { std::env::set_var(self.key, value) } - } - None => { - // SAFETY: validation runs this integration test with --test-threads=1. - unsafe { std::env::remove_var(self.key) } - } - } - } -} - -// Serialize env mutation against every other aggregated suite via the -// single crate-wide SHARED_ENV_LOCK (these tests use an `EnvGuard` struct -// that does not itself hold a lock). Poison is recovered so a panic -// elsewhere cannot wedge the suite. -fn __shared_env_lock() -> std::sync::MutexGuard<'static, ()> { - crate::SHARED_ENV_LOCK - .get_or_init(|| std::sync::Mutex::new(())) - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) -} - - #[tokio::test] -async fn local_service_covers_mocked_bootstrap_assets_diagnostics_and_embed() { - let _env_lock = __shared_env_lock(); - let tmp = tempdir().expect("tempdir"); - let fake_bin_dir = tmp.path().join("fake-bin"); - std::fs::create_dir_all(&fake_bin_dir).expect("fake bin dir"); - let fake_ollama = write_stub_script(&fake_bin_dir, "ollama", "#!/bin/sh\nexit 0\n"); - let fake_mlx = write_stub_script(&fake_bin_dir, "mlx_lm", "#!/bin/sh\nexit 0\n"); - let _ollama_bin = EnvVarGuard::set("OLLAMA_BIN", &fake_ollama); - let _mlx_bin = EnvVarGuard::set("MLX_LM_BIN", &fake_mlx); - let _python = EnvVarGuard::unset("PYTHON"); - let _whisper = EnvVarGuard::unset("WHISPER_BIN"); - let _piper = EnvVarGuard::unset("PIPER_BIN"); - - let (base, state) = serve_mock().await; - let _ollama_url = EnvVarGuard::set("OPENHUMAN_OLLAMA_BASE_URL", &base); - let mut config = temp_config(&tmp); - config.local_ai.runtime_enabled = true; - config.local_ai.opt_in_confirmed = true; - config.local_ai.provider = "ollama".to_string(); - config.local_ai.base_url = Some(base.clone()); - config.local_ai.chat_model_id = "gemma3:1b-it-qat".to_string(); - config.local_ai.model_id = "gemma3:1b-it-qat".to_string(); - config.local_ai.embedding_model_id = "bge-m3".to_string(); - config.local_ai.preload_embedding_model = true; - config.local_ai.preload_tts_voice = false; - config.local_ai.tts_download_url = Some(format!("{base}/asset/tts")); - - let runtime = openhuman_core::inference::local_runtime_config(&config); - let service = LocalAiService::new(&runtime); - service.bootstrap(&runtime).await; - let status = service.status(); - assert_eq!(status.state, "ready"); - assert_eq!(status.embedding_state, "ready"); - assert_eq!(status.provider, "ollama"); - assert_eq!( - status.model_path.as_deref(), - Some("ollama://gemma3:1b-it-qat") - ); - - let assets = service.assets_status(&runtime).await.expect("assets status"); - assert_eq!(assets.chat.state, "ready"); - assert_eq!(assets.embedding.state, "ready"); - assert_eq!(assets.vision.state, "disabled"); - assert!( - matches!(assets.tts.state.as_str(), "ondemand" | "ready"), - "tts state should be on-demand or already resolved, got {}", - assets.tts.state - ); - assert!(assets.ollama_available); - - let progress = service - .downloads_progress(&runtime) - .await - .expect("downloads progress"); - assert_eq!(progress.chat.state, "ready"); - assert_eq!(progress.embedding.state, "ready"); - - let diagnostics = service.diagnostics(&runtime).await.expect("diagnostics"); - assert_eq!(diagnostics["ollama_running"], true); - assert_eq!(diagnostics["expected"]["chat_found"], true); - assert_eq!(diagnostics["expected"]["embedding_found"], true); - assert!(diagnostics["ollama_binary_path"] - .as_str() - .unwrap() - .contains("ollama")); - assert_eq!( - diagnostics["installed_models"] - .as_array() - .expect("installed models") - .len(), - 2 - ); - - let embedded = service - .embed( - &runtime, - &[ - " first input ".to_string(), - "".to_string(), - "second input".to_string(), - ], - ) - .await - .expect("mocked embed"); - assert_eq!(embedded.model_id, "bge-m3"); - assert_eq!(embedded.dimensions, 1024); - assert_eq!(embedded.vectors.len(), 2); - - let seen = state.requests.lock().expect("requests"); - assert!(seen.iter().any(|req| req.path == "/api/show" - && req - .body - .get("name") - .or_else(|| req.body.get("model")) - .and_then(Value::as_str) - == Some("___nonexistent_probe___"))); - let embed = seen - .iter() - .find(|req| req.path == "/api/embed") - .expect("embed request"); - assert_eq!(embed.body["model"], "bge-m3"); - assert_eq!(embed.body["input"], json!(["first input", "second input"])); -} - -async fn serve_mock() -> (String, MockState) { - let state = MockState::default(); - let app = Router::new() - .route("/v1/chat/completions", post(chat_completions)) - .route("/api/tags", get(ollama_tags)) - .route("/api/show", post(ollama_show)) - .route("/api/pull", post(ollama_pull)) - .route("/api/embed", post(ollama_embed)) - .route("/asset/stt", get(asset_bytes)) - .route("/asset/tts", get(asset_bytes)) - .with_state(state.clone()); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("bind mock"); - let addr = listener.local_addr().expect("addr"); - tokio::spawn(async move { - axum::serve(listener, app).await.expect("serve mock"); - }); - (format!("http://{addr}"), state) -} - -async fn chat_completions( - State(state): State, - headers: HeaderMap, - Json(body): Json, -) -> impl IntoResponse { - remember(&state, "/v1/chat/completions", &headers, body.clone()); - match body["model"].as_str().unwrap_or_default() { - "stream-tools" => sse_response( - [ - r#"data: {"choices":[{"delta":{"content":"hello ","reasoning_content":"think ","tool_calls":[{"index":0,"id":"call_round26","function":{"name":"lookup","arguments":"{\"q\""}}]}}]}"#, - r#"data: {"choices":[{"delta":{"content":"world","reasoning_content":"more","tool_calls":[{"index":0,"function":{"arguments":":\"rust\"}"}}]}}],"usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15},"openhuman":{"usage":{"input_tokens":11,"output_tokens":6,"cached_input_tokens":4},"billing":{"charged_amount_usd":0.01}}}"#, - "data: [DONE]", - ] - .join("\n\n"), - ) - .into_response(), - "json-stream" => ( - [(header::CONTENT_TYPE, "application/json")], - Json(json!({ - "choices": [{"message": {"content": "json fallback ok"}}], - "usage": { - "prompt_tokens": 8, - "completion_tokens": 4, - "total_tokens": 12, - "prompt_tokens_details": {"cached_tokens": 3} - } - })), - ) - .into_response(), - "tool-retry" => { - let mut attempts = state.tool_retry_attempts.lock().expect("attempts"); - *attempts += 1; - if body.get("tools").is_some() { - ( - StatusCode::BAD_REQUEST, - "this model does not support tools or tool_choice", - ) - .into_response() - } else { - sse_response( - [ - r#"data: {"choices":[{"delta":{"content":"retried ok"}}]}"#, - "data: [DONE]", - ] - .join("\n\n"), - ) - .into_response() - } - } - _ => Json(json!({"choices":[{"message":{"content":"ok"}}]})).into_response(), - } -} - -async fn ollama_tags(State(state): State, headers: HeaderMap) -> impl IntoResponse { - remember(&state, "/api/tags", &headers, json!({})); - Json(json!({ - "models": [ - { - "name": "gemma3:1b-it-qat", - "model": "gemma3:1b-it-qat", - "modified_at": "2026-05-30T00:00:00Z", - "size": 1234, - "digest": "sha256:chat" - }, - { - "name": "bge-m3:latest", - "model": "bge-m3:latest", - "modified_at": "2026-05-30T00:00:00Z", - "size": 5678, - "digest": "sha256:embed" - } - ] - })) -} - -async fn ollama_show( - State(state): State, - headers: HeaderMap, - Json(body): Json, -) -> impl IntoResponse { - remember(&state, "/api/show", &headers, body.clone()); - let model = body - .get("model") - .or_else(|| body.get("name")) - .and_then(Value::as_str) - .unwrap_or_default(); - if model == "___nonexistent_probe___" { - return (StatusCode::NOT_FOUND, "model not found").into_response(); - } - Json(json!({ - "model_info": { - "llama.context_length": if model.starts_with("bge-m3") { 8192 } else { 4096 } - } - })) - .into_response() -} - -async fn ollama_pull( - State(state): State, - headers: HeaderMap, - Json(body): Json, -) -> impl IntoResponse { - remember(&state, "/api/pull", &headers, body); - sse_response( - [ - r#"{"status":"downloading","digest":"sha256:a","total":100,"completed":100}"#, - r#"{"status":"success"}"#, - ] - .join("\n"), - ) -} - -async fn ollama_embed( - State(state): State, - headers: HeaderMap, - Json(body): Json, -) -> impl IntoResponse { - remember(&state, "/api/embed", &headers, body); - Json(json!({ - "model": "bge-m3", - "embeddings": [vec![0.1; 1024], vec![0.2; 1024]] - })) -} - -async fn asset_bytes() -> impl IntoResponse { - Response::builder() - .status(StatusCode::OK) - .body(Body::from(vec![7u8; 1024])) - .expect("asset response") -} - -fn sse_response(body: String) -> Response { - Response::builder() - .status(StatusCode::OK) - .header(header::CONTENT_TYPE, "text/event-stream") - .body(Body::from(body)) - .expect("sse response") -} - -fn remember(state: &MockState, path: &str, headers: &HeaderMap, body: Value) { - state.requests.lock().expect("requests").push(SeenRequest { - path: path.to_string(), - auth: auth_header(headers), - body, - }); -} - -fn auth_header(headers: &HeaderMap) -> Option { - headers - .get(header::AUTHORIZATION) - .or_else(|| headers.get("x-api-key")) - .and_then(|value| value.to_str().ok()) - .map(ToOwned::to_owned) -} - -fn tool_spec(name: &str) -> ToolSpec { - ToolSpec { - name: name.to_string(), - description: format!("{name} tool"), - parameters: json!({ - "type": "object", - "properties": { - "q": {"type": "string"} - } - }), - } -} - -fn temp_config(tmp: &TempDir) -> Config { - let root = tmp.path().join(".openhuman"); - std::fs::create_dir_all(root.join("workspace")).expect("workspace dir"); - let mut config = Config::default(); - config.config_path = root.join("config.toml"); - config.workspace_dir = root.join("workspace"); - config.secrets.encrypt = false; - config.api_url = Some("http://127.0.0.1:9".to_string()); - config -} - -fn write_stub_script(dir: &Path, name: &str, body: &str) -> PathBuf { - let path = dir.join(name); - std::fs::write(&path, body).expect("write stub script"); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let mut perms = std::fs::metadata(&path).expect("metadata").permissions(); - perms.set_mode(0o755); - std::fs::set_permissions(&path, perms).expect("chmod"); - } - path -} diff --git a/tests/raw_coverage/inference_voice_http_round23_raw_coverage_e2e.rs b/tests/raw_coverage/inference_voice_http_round23_raw_coverage_e2e.rs index 4c06e3e53f2..a599ee3f1ea 100644 --- a/tests/raw_coverage/inference_voice_http_round23_raw_coverage_e2e.rs +++ b/tests/raw_coverage/inference_voice_http_round23_raw_coverage_e2e.rs @@ -5,7 +5,6 @@ //! download endpoints. use std::collections::HashMap; -use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, OnceLock}; use axum::body::Body; @@ -25,9 +24,6 @@ use openhuman_core::security::credentials::{ AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME, }; use openhuman_core::inference::http; -use openhuman_core::inference::host_runtime::{ - local_ai_assets_status, local_ai_downloads_progress, LocalAiService, -}; use openhuman_core::voice::streaming::handle_dictation_ws; use serde_json::{json, Value}; use tempfile::{tempdir, TempDir}; @@ -50,13 +46,6 @@ impl EnvVarGuard { unsafe { std::env::set_var(key, value) }; Self { key, previous } } - - fn unset(key: &'static str) -> Self { - let previous = std::env::var_os(key); - // SAFETY: mutation is serialized by `env_lock()` (see below). - unsafe { std::env::remove_var(key) }; - Self { key, previous } - } } impl Drop for EnvVarGuard { @@ -240,79 +229,6 @@ async fn dictation_ws_empty_stop_and_audio_cap_do_not_load_whisper() { .contains("Recording limit reached")); } -#[tokio::test] -async fn local_service_assets_report_state_from_fake_files_and_binaries() { - let _env = env_lock(); - let (base, _state) = serve_mock().await; - let tmp = tempdir().expect("tempdir"); - let scripts = tempdir().expect("scripts"); - write_stub_script(scripts.path(), "ollama", "#!/bin/sh\nexit 42\n"); - write_stub_script(scripts.path(), "python", "#!/bin/sh\nexit 42\n"); - write_stub_script(scripts.path(), "python3", "#!/bin/sh\nexit 42\n"); - write_stub_script(scripts.path(), "mlx_lm.generate", "#!/bin/sh\nexit 42\n"); - write_stub_script(scripts.path(), "piper", "#!/bin/sh\nexit 42\n"); - - // The `stt` asset slot still exists (the hosted-STT migration left the - // generic local-AI asset plumbing in place), so a present file on disk - // must still report "ready" — only the transcription engine behind it is - // gone. Nothing reads this file any more; it exists to drive the state - // machine. - let fake_model = tmp.path().join("fake-stt-asset.bin"); - std::fs::write(&fake_model, b"not a real stt model").expect("fake model"); - - let mut config = temp_config(&tmp); - config.local_ai.runtime_enabled = true; - config.local_ai.opt_in_confirmed = true; - config.local_ai.provider = "ollama".to_string(); - config.local_ai.base_url = Some(base.clone()); - config.local_ai.selected_tier = Some("custom".to_string()); - config.local_ai.chat_model_id = "gemma3:1b-it-qat".to_string(); - config.local_ai.embedding_model_id = "bge-m3".to_string(); - config.local_ai.vision_model_id = "vision-ready".to_string(); - config.local_ai.stt_model_id = fake_model.display().to_string(); - config.local_ai.tts_voice_id = "round23-voice".to_string(); - config.local_ai.tts_download_url = Some(format!("{base}/asset/tts")); - config.save().await.expect("save config"); - - let _path = EnvVarGuard::set("PATH", scripts.path()); - let _workspace = EnvVarGuard::set("OPENHUMAN_WORKSPACE", config.config_path.parent().unwrap()); - let _ollama_base = EnvVarGuard::set("OPENHUMAN_OLLAMA_BASE_URL", &base); - let _piper_bin = EnvVarGuard::unset("PIPER_BIN"); - let _ollama_bin = EnvVarGuard::unset("OLLAMA_BIN"); - - let runtime = openhuman_core::inference::local_runtime_config(&config); - let service = LocalAiService::new(&runtime); - let assets = service.assets_status(&runtime).await.expect("assets"); - assert!(assets.ollama_available); - assert_eq!(assets.chat.state, "ready"); - assert_eq!(assets.embedding.state, "ready"); - // Since #5253 (vision-capable routing), the configured "vision-ready" id - // passes `is_vision_capable` (name carries the vision marker) instead of - // being rejected by the old MVP allowlist — and the mock's /api/tags - // advertises it, so an Ondemand-mode vision model that is present reports - // "ready", not "ondemand". - assert_eq!(assets.vision.state, "ready"); - assert_eq!(assets.tts.state, "ondemand"); - - let progress = service.downloads_progress(&runtime).await.expect("progress"); - assert_eq!(progress.tts.state, "ondemand"); - - // No transcription assertion here any more: `transcribe_with_prompt` is a - // hosted call to the backend proxy since the whisper.cpp engine was - // deleted, so there is no local binary to stub and nothing this offline - // test can drive. Hosted STT is covered where the backend is mocked. - - assert_eq!( - local_ai_downloads_progress(&config) - .await - .expect("ops progress") - .value - .tts - .state, - "ondemand" - ); -} - async fn serve_mock() -> (String, MockState) { let state = MockState::default(); let app = Router::new() @@ -474,15 +390,3 @@ fn store_app_session(config: &Config) { .expect("store app session"); } -fn write_stub_script(dir: &Path, name: &str, body: &str) -> PathBuf { - let path = dir.join(name); - std::fs::write(&path, body).expect("write stub"); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let mut perms = std::fs::metadata(&path).expect("metadata").permissions(); - perms.set_mode(0o755); - std::fs::set_permissions(&path, perms).expect("chmod"); - } - path -} diff --git a/tests/raw_coverage/memory_source_scope_bus_raw_coverage_e2e.rs b/tests/raw_coverage/memory_source_scope_bus_raw_coverage_e2e.rs deleted file mode 100644 index fa996c0d8a2..00000000000 --- a/tests/raw_coverage/memory_source_scope_bus_raw_coverage_e2e.rs +++ /dev/null @@ -1,112 +0,0 @@ -//! Raw integration coverage for the host→bus source-scope rendering that the -//! retrieval handlers rewired onto in #5854. -//! -//! #5854 moved `read_rpc/chunks.rs`'s recall and the `tree/retrieval/rpc.rs` -//! handlers off a direct engine call and onto -//! `binding.provider().as_retrieval()` with an **explicit** -//! `source_scope::as_bus_scope()` argument. The scope used to be a task-local -//! the engine read for itself; once memory is a separately compiled module -//! with its own statics, a task-local set on this side is invisible on the -//! other, so the value has to cross the bus. -//! -//! `as_bus_scope` is the join, and its contract has one asymmetry that is easy -//! to get backwards and impossible to see from a passing build: -//! -//! - **`None` means unrestricted** and must stay `None`. -//! - **`Some(SourceScope)` with an empty allow list denies every -//! source-attributed item** (`SourceScope`'s own fail-closed rule). -//! -//! So collapsing "no restriction" onto `Some(SourceScope::default())` inverts -//! the policy: recall silently returns nothing instead of everything. Both -//! values are well-formed, both type-check, and the handlers report an empty -//! page as a legitimate answer — so the failure surfaces as "memory forgot -//! everything", with nothing in the logs. -//! -//! Nothing asserted this before: every occurrence of `as_bus_scope` in the tree -//! is a call site or a comment. - -use std::collections::HashSet; - -use openhuman_core::memory::source_scope::{as_bus_scope, with_source_scope}; - -/// Outside any scope, and for an explicit `None`, the rendering stays `None`. -/// -/// This is the inversion guard. `Some(empty)` here would be a scope that denies -/// everything, which is the exact opposite of what an unscoped turn means. -#[tokio::test] -async fn unrestricted_recall_renders_as_no_scope_not_an_empty_allowlist() { - assert!( - as_bus_scope().is_none(), - "outside any scope the bus argument must be None (unrestricted); \ - Some(empty) is SourceScope's deny-all and would blank recall" - ); - - with_source_scope(None, async { - assert!( - as_bus_scope().is_none(), - "an explicit None allowlist must render as None, not as an empty \ - SourceScope" - ); - }) - .await; -} - -/// A profile that selected no sources is a real restriction, and must NOT be -/// flattened into the unrestricted `None`. -/// -/// The mirror of the test above: these two inputs are the ones that must not be -/// confused, in either direction. -#[tokio::test] -async fn an_empty_allowlist_renders_as_a_scope_that_denies_every_source() { - with_source_scope(Some(vec![]), async { - let scope = as_bus_scope().expect( - "an empty allowlist is a restriction the driver must be told about, \ - not the absence of one", - ); - assert!( - scope.is_empty(), - "an empty allowlist must cross the bus as an empty SourceScope" - ); - assert!( - !scope.allows_source_id("mem_src:anything:item-1"), - "an empty scope denies all source-attributed content" - ); - }) - .await; -} - -/// The allowlist reaches the driver intact, and matches by the bus's own rule. -/// -/// `SourceScope::allows_source_id` accepts an outright id match or the -/// `mem_src::` composite the reader-based sources emit. Asserting -/// through that predicate — rather than comparing the `allow` vector — is what -/// ties the host's rendering to the matching the driver will actually perform. -#[tokio::test] -async fn the_allowlist_crosses_the_bus_and_matches_by_the_drivers_rule() { - let allowed = vec!["gmail:work".to_string(), "src-abc".to_string()]; - - with_source_scope(Some(allowed.clone()), async { - let scope = as_bus_scope().expect("a non-empty allowlist must render as Some"); - - let carried: HashSet<&str> = scope.allow.iter().map(String::as_str).collect(); - assert_eq!( - carried, - allowed.iter().map(String::as_str).collect::>(), - "every allowlisted source must reach the driver, and no others" - ); - - assert!( - scope.allows_source_id("src-abc"), - "an outright id match is in scope" - ); - assert!( - scope.allows_source_id("mem_src:src-abc:item-1"), - "the mem_src composite the reader-based sources emit is in scope" - ); - assert!( - !scope.allows_source_id("src-xyz"), - "a source outside the allowlist stays out" - ); - }) - .await; -} diff --git a/tests/raw_coverage/memory_sources_closure_round23_raw_coverage_e2e.rs b/tests/raw_coverage/memory_sources_closure_round23_raw_coverage_e2e.rs deleted file mode 100644 index 5533ae5617d..00000000000 --- a/tests/raw_coverage/memory_sources_closure_round23_raw_coverage_e2e.rs +++ /dev/null @@ -1,158 +0,0 @@ -use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex, OnceLock}; - -use openhuman_core::config::Config; -use openhuman_core::config::rpc as config_rpc; -use openhuman_core::memory::sources::readers::SourceReader; -use openhuman_core::memory::sources::{ - self as memory_sources, ContentType, MemorySourceEntry, MemorySourcePatch, SourceKind, -}; -use tempfile::{Builder, TempDir}; - -static ENV_LOCK: &OnceLock> = &crate::SHARED_ENV_LOCK; -static MEMORY_SEAMS_INIT: OnceLock<()> = OnceLock::new(); - -fn ensure_memory_seams() { - MEMORY_SEAMS_INIT.get_or_init(|| { - std::thread::Builder::new() - .name("round23-memory-source-seams".to_string()) - .stack_size(8 * 1024 * 1024) - .spawn(|| { - }) - .expect("spawn round23 memory source seam installer") - .join() - .expect("round23 memory source seam installer panicked"); - }); -} - -struct EnvGuard { - key: &'static str, - old: Option, -} - -impl EnvGuard { - fn set_path(key: &'static str, path: &Path) -> Self { - let old = std::env::var(key).ok(); - unsafe { std::env::set_var(key, path.as_os_str()) }; - Self { key, old } - } - - fn set(key: &'static str, value: impl Into) -> Self { - let old = std::env::var(key).ok(); - unsafe { std::env::set_var(key, value.into()) }; - Self { key, old } - } - - fn unset(key: &'static str) -> Self { - let old = std::env::var(key).ok(); - unsafe { std::env::remove_var(key) }; - Self { key, old } - } -} - -impl Drop for EnvGuard { - fn drop(&mut self) { - match &self.old { - Some(value) => unsafe { std::env::set_var(self.key, value) }, - None => unsafe { std::env::remove_var(self.key) }, - } - } -} - -struct Harness { - _tmp: TempDir, - root: PathBuf, - _guards: Vec, -} - -impl Harness { - async fn config(&self) -> openhuman_core::config::Config { - config_rpc::load_config_with_timeout() - .await - .expect("isolated config should load") - } -} - -fn env_lock() -> std::sync::MutexGuard<'static, ()> { - ENV_LOCK - .get_or_init(|| Mutex::new(())) - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) -} - -fn tempdir() -> TempDir { - std::fs::create_dir_all("target").expect("target dir"); - Builder::new() - .prefix("memory-sources-closure-round23-") - .tempdir_in("target") - .expect("tempdir") -} - -fn setup() -> Harness { - let tmp = tempdir(); - let root = tmp.path().join("openhuman"); - std::fs::create_dir_all(&root).expect("root"); - std::fs::write( - root.join("config.toml"), - r#"api_url = "http://127.0.0.1:9" -default_model = "round23-memory-sources" -default_temperature = 0.2 - -[secrets] -encrypt = false - -[memory] -provider = "none" -embedding_provider = "none" -embedding_model = "none" -embedding_dimensions = 0 -auto_save = false - -[memory_tree] -embedding_strict = false -"#, - ) - .expect("config"); - let guards = vec![ - EnvGuard::set_path("OPENHUMAN_WORKSPACE", &root), - EnvGuard::set_path("HOME", tmp.path()), - EnvGuard::set("OPENHUMAN_MEMORY_EMBED_STRICT", "false"), - EnvGuard::set("OPENHUMAN_MEMORY_EMBED_ENDPOINT", ""), - EnvGuard::set("OPENHUMAN_MEMORY_EMBED_MODEL", ""), - EnvGuard::unset("OPENHUMAN_API_URL"), - EnvGuard::unset("BACKEND_URL"), - EnvGuard::unset("VITE_BACKEND_URL"), - ]; - Harness { - _tmp: tmp, - root, - _guards: guards, - } -} - -fn source_entry(id: &str, kind: SourceKind) -> MemorySourceEntry { - MemorySourceEntry { - id: id.to_string(), - kind, - label: format!("{id} label"), - enabled: true, - toolkit: None, - connection_id: None, - path: None, - glob: None, - url: None, - branch: None, - paths: Vec::new(), - query: None, - since_days: None, - max_items: None, - max_commits: None, - max_issues: None, - max_prs: None, - selector: None, - max_tokens_per_sync: None, - max_cost_per_sync_usd: None, - sync_depth_days: None, - } -} - diff --git a/tests/raw_coverage/memory_sources_readers_round21_raw_coverage_e2e.rs b/tests/raw_coverage/memory_sources_readers_round21_raw_coverage_e2e.rs deleted file mode 100644 index ff071cd7751..00000000000 --- a/tests/raw_coverage/memory_sources_readers_round21_raw_coverage_e2e.rs +++ /dev/null @@ -1,273 +0,0 @@ -use std::path::{Path, PathBuf}; -use std::sync::{Mutex, OnceLock}; - -use openhuman_core::config::Config; -use openhuman_core::memory::sources::readers::SourceReader; -use openhuman_core::memory::sources::{ContentType, MemorySourceEntry, SourceKind}; -use tempfile::{Builder, TempDir}; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; - -static ENV_LOCK: &OnceLock> = &crate::SHARED_ENV_LOCK; - -struct EnvGuard { - key: &'static str, - old: Option, -} - -impl EnvGuard { - fn set_path(key: &'static str, value: &Path) -> Self { - let old = std::env::var(key).ok(); - unsafe { std::env::set_var(key, value.as_os_str()) }; - Self { key, old } - } -} - -impl Drop for EnvGuard { - fn drop(&mut self) { - match &self.old { - Some(value) => unsafe { std::env::set_var(self.key, value) }, - None => unsafe { std::env::remove_var(self.key) }, - } - } -} - -fn env_lock() -> std::sync::MutexGuard<'static, ()> { - ENV_LOCK - .get_or_init(|| Mutex::new(())) - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) -} - -fn tempdir() -> TempDir { - std::fs::create_dir_all("target").expect("target dir"); - Builder::new() - .prefix("memory-sources-readers-round21-") - .tempdir_in("target") - .expect("tempdir") -} - -fn config(tmp: &TempDir) -> Config { - let mut config = Config::default(); - config.workspace_dir = tmp.path().join("workspace"); - config.action_dir = tmp.path().join("workspace"); - config.config_path = tmp.path().join("config.toml"); - config -} - -fn source_entry(id: &str, kind: SourceKind) -> MemorySourceEntry { - MemorySourceEntry { - id: id.to_string(), - kind, - label: format!("{id} label"), - enabled: true, - toolkit: None, - connection_id: None, - path: None, - glob: None, - url: None, - branch: None, - paths: Vec::new(), - query: None, - since_days: None, - max_items: None, - max_commits: None, - max_issues: None, - max_prs: None, - selector: None, - max_tokens_per_sync: None, - max_cost_per_sync_usd: None, - sync_depth_days: None, - } -} - -async fn one_response_server( - status: &'static str, - headers: &'static str, - body: Vec, -) -> (String, tokio::task::JoinHandle<()>) { - let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)) - .await - .expect("bind fixture"); - let url = format!("http://{}", listener.local_addr().expect("addr")); - let task = tokio::spawn(async move { - if let Ok((mut stream, _)) = listener.accept().await { - let mut req = [0_u8; 1024]; - let _ = stream.read(&mut req).await; - let has_content_length = headers - .lines() - .any(|line| line.to_ascii_lowercase().starts_with("content-length:")); - let mut response = format!("HTTP/1.1 {status}\r\n"); - if !has_content_length { - response.push_str(&format!("content-length: {}\r\n", body.len())); - } - if !headers.is_empty() { - response.push_str(headers); - response.push_str("\r\n"); - } - response.push_str("\r\n"); - let _ = stream.write_all(response.as_bytes()).await; - let _ = stream.write_all(&body).await; - let _ = stream.shutdown().await; - } - }); - (url, task) -} - -#[tokio::test] -async fn round21_rss_reader_rejects_private_hosts_before_fetching() { - let _lock = env_lock(); - let tmp = tempdir(); - let config = config(&tmp); - let reader = openhuman_core::memory::sources::readers::rss::RssReader::new(); - - let (status_url, status_server) = - one_response_server("503 Service Unavailable", "", b"down".to_vec()).await; - let status_err = reader - .list_items( - &MemorySourceEntry { - url: Some(status_url), - ..source_entry("rss-status", SourceKind::RssFeed) - }, - &config.workspace_dir, - ) - .await - .expect_err("private feed host rejected before fetch") - .to_string(); - assert!( - status_err.contains("public host"), - "private RSS hosts must be rejected before fetching: {status_err}" - ); - status_server.abort(); -} - -#[tokio::test] -async fn round21_github_reader_covers_commit_issue_comments_and_error_paths() { - let _lock = env_lock(); - let tmp = tempdir(); - let config = config(&tmp); - let bin = tmp.path().join("bin"); - std::fs::create_dir_all(&bin).expect("bin dir"); - write_fake_gh(&bin.join("gh")); - write_fake_git(&bin.join("git")); - let old_path = std::env::var("PATH").unwrap_or_default(); - let _path = EnvGuard::set_path("PATH", Path::new(&format!("{}:{old_path}", bin.display()))); - - let reader = openhuman_core::memory::sources::readers::github::GithubReader; - let entry = MemorySourceEntry { - url: Some("https://github.com/tinyhumansai/openhuman".to_string()), - ..source_entry("github-round21", SourceKind::GithubRepo) - }; - - let items = reader - .list_items(&entry, &config.workspace_dir) - .await - .expect("list items"); - assert!(items.iter().any(|item| item.id == "commit:abc123")); - assert!(items.iter().any(|item| item.id == "issue:42")); - assert!(items.iter().any(|item| item.id == "pr:43")); - - let commit = reader - .read_item(&entry, "commit:abc123", &config.workspace_dir) - .await - .expect("read commit"); - assert_eq!(commit.content_type, ContentType::Markdown); - assert!(commit.body.contains("Round21 commit subject")); - - let issue = reader - .read_item(&entry, "issue:42", &config.workspace_dir) - .await - .expect("read issue with comments"); - assert!(issue.body.contains("## Comments")); - assert!(issue.body.contains("Looks good from the fixture")); - assert_eq!( - issue - .metadata - .get("labels") - .and_then(|value| value.as_array()) - .map(Vec::len), - Some(0) - ); - - let bad_pr = reader - .read_item(&entry, "pr:not-a-number", &config.workspace_dir) - .await - .expect_err("bad pr number rejected") - .to_string(); - assert!(bad_pr.contains("invalid PR number")); -} - -fn write_fake_gh(path: &PathBuf) { - let script = r#"#!/usr/bin/env bash -set -euo pipefail -if [[ "${1:-}" == "--version" ]]; then - echo "gh version 2.0.0" - exit 0 -fi -if [[ "${1:-}" != "api" ]]; then - echo "unsupported gh command" >&2 - exit 2 -fi -arg="${2:-}" -# Match on the base resource path, ignoring per_page/page/state params. -case "$arg" in - repos/tinyhumansai/openhuman/commits\?*) - cat <<'JSON' -[{"sha":"abc123","commit":{"message":"Round21 commit subject\n\nBody line","author":{"name":"Ada","email":"ada@example.test","date":"2026-05-30T00:00:00Z"},"committer":{"name":"Ada","email":"ada@example.test","date":"2026-05-30T00:00:00Z"}}}] -JSON - ;; - repos/tinyhumansai/openhuman/issues\?*) - cat <<'JSON' -[{"number":42,"title":"Round21 issue","body":"Issue body","state":"open","user":{"login":"octo"},"labels":[],"created_at":"2026-05-30T00:00:00Z","updated_at":"2026-05-30T00:01:00Z","pull_request":null}] -JSON - ;; - repos/tinyhumansai/openhuman/pulls\?*) - cat <<'JSON' -[{"number":43,"title":"Round21 PR","body":"PR body","state":"open","user":{"login":"octo"},"labels":[],"created_at":"2026-05-30T00:00:00Z","updated_at":"2026-05-30T00:02:00Z","merged_at":null,"comments":1}] -JSON - ;; - repos/tinyhumansai/openhuman/commits/abc123) - cat <<'JSON' -{"sha":"abc123","commit":{"message":"Round21 commit subject\n\nBody line","author":{"name":"Ada","email":"ada@example.test","date":"2026-05-30T00:00:00Z"},"committer":{"name":"Grace","email":"grace@example.test","date":"2026-05-30T00:03:00Z"}}} -JSON - ;; - repos/tinyhumansai/openhuman/issues/42) - cat <<'JSON' -{"number":42,"title":"Round21 issue","body":"Issue body","state":"open","user":{"login":"octo"},"labels":[],"created_at":"2026-05-30T00:00:00Z","updated_at":"2026-05-30T00:01:00Z","pull_request":null} -JSON - ;; - repos/tinyhumansai/openhuman/issues/42/comments\?*) - cat <<'JSON' -[{"user":{"login":"reviewer"},"body":"Looks good from the fixture","created_at":"2026-05-30T00:04:00Z"}] -JSON - ;; - *) - echo "unexpected gh api path: $arg" >&2 - exit 3 - ;; -esac -"#; - std::fs::write(path, script).expect("write fake gh"); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let mut perms = std::fs::metadata(path).expect("metadata").permissions(); - perms.set_mode(0o755); - std::fs::set_permissions(path, perms).expect("chmod fake gh"); - } -} - -fn write_fake_git(path: &PathBuf) { - let script = r#"#!/usr/bin/env bash -set -euo pipefail -echo "git disabled for github reader fixture" >&2 -exit 42 -"#; - std::fs::write(path, script).expect("write fake git"); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let mut perms = std::fs::metadata(path).expect("metadata").permissions(); - perms.set_mode(0o755); - std::fs::set_permissions(path, perms).expect("chmod fake git"); - } -} diff --git a/tests/raw_coverage/memory_sync_round23_raw_coverage_e2e.rs b/tests/raw_coverage/memory_sync_round23_raw_coverage_e2e.rs index 52126c074f9..3af15e45e6b 100644 --- a/tests/raw_coverage/memory_sync_round23_raw_coverage_e2e.rs +++ b/tests/raw_coverage/memory_sync_round23_raw_coverage_e2e.rs @@ -53,18 +53,13 @@ use std::collections::HashMap; use std::sync::{Mutex, OnceLock}; -use serde_json::{json, Value}; use tempfile::TempDir; use openhuman_core::config::Config; -use openhuman_core::integrations::composio::identity_store::{ - delete_connected_identity_facets, load_connected_identities, persist_provider_profile, -}; use openhuman_core::integrations::composio::ops::composio_get_user_profile; use openhuman_core::security::credentials::{ AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME, }; -use tinymemory_api::composio::{render_connected_identities_section, ProviderUserProfile}; static ENV_LOCK: &OnceLock> = &crate::SHARED_ENV_LOCK; static MEMORY_SEAMS_INIT: OnceLock<()> = OnceLock::new(); diff --git a/tests/raw_coverage/owned_domain_raw_coverage_e2e.rs b/tests/raw_coverage/owned_domain_raw_coverage_e2e.rs deleted file mode 100644 index f97bf1bf657..00000000000 --- a/tests/raw_coverage/owned_domain_raw_coverage_e2e.rs +++ /dev/null @@ -1,586 +0,0 @@ -//! Focused raw-line coverage for owned domains with local-only dependencies. -//! -//! This suite drives public APIs for the agent, inference, and composio slices -//! against temp directories and loopback Axum servers. It avoids live providers. - -use std::sync::{Arc, Mutex}; - -use axum::extract::State; -use axum::http::{HeaderMap, StatusCode}; -use axum::response::{IntoResponse, Response}; -use axum::routing::{delete, get, post}; -use axum::{Json, Router}; -use serde_json::{json, Map, Value}; -use tempfile::tempdir; - -use openhuman_core::config::{ - CapabilityProviderConfig, CapabilityProviderTrustState, Config, McpServerConfig, -}; -use openhuman_core::integrations::IntegrationClient; -use openhuman_core::tools::registry::{ - all_tool_registry_controller_schemas, all_tool_registry_registered_controllers, - capability_provider_by_id, capability_provider_diagnostics, get_tool, - is_capability_provider_trusted_enabled, list_capability_providers, list_tools, - normalize_capability_provider_id, -}; -use openhuman_core::tools::registry::{denials as tool_registry_denials, ops as tool_registry_ops}; - -static OWNED_DOMAIN_ENV_LOCK: &std::sync::OnceLock> = &crate::SHARED_ENV_LOCK; - -#[derive(Clone, Default)] -struct ProviderMockState { - chat_requests: Arc>>, - response_requests: Arc>>, - auth_headers: Arc>>>, - user_agents: Arc>>>, -} - -#[derive(Clone, Default)] -struct ComposioMockState { - requests: Arc, Option)>>>, -} - -async fn serve_provider_mock() -> (String, ProviderMockState) { - let state = ProviderMockState::default(); - let app = Router::new() - .route("/v1/chat/completions", post(provider_chat)) - .route("/v1/responses", post(provider_responses)) - .with_state(state.clone()); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("bind provider mock"); - let addr = listener.local_addr().expect("provider mock addr"); - tokio::spawn(async move { - axum::serve(listener, app) - .await - .expect("provider mock serve"); - }); - (format!("http://{addr}/v1"), state) -} - -async fn provider_chat( - State(state): State, - headers: HeaderMap, - Json(body): Json, -) -> Response { - state - .auth_headers - .lock() - .expect("auth headers") - .push(header(&headers, "authorization")); - state - .user_agents - .lock() - .expect("user agents") - .push(header(&headers, "user-agent")); - state - .chat_requests - .lock() - .expect("chat requests") - .push(body.clone()); - - if body.pointer("/stream").and_then(Value::as_bool) == Some(true) { - return Json(json!({ - "choices": [{ - "message": { - "content": "stream fallback body", - "reasoning_content": "stream thinking" - } - }], - "usage": { - "prompt_tokens": 3, - "completion_tokens": 4, - "total_tokens": 7, - "prompt_tokens_details": { "cached_tokens": 2 } - } - })) - .into_response(); - } - - if body.get("tools").is_some() { - return ( - StatusCode::BAD_REQUEST, - Json(json!({ "error": "unknown parameter: tools" })), - ) - .into_response(); - } - - if body.pointer("/model").and_then(Value::as_str) == Some("missing-chat") { - return ( - StatusCode::NOT_FOUND, - Json(json!({ "error": "chat completions unavailable" })), - ) - .into_response(); - } - - Json(json!({ - "choices": [{ - "message": { - "content": "hiddenvisible answer", - "reasoning_content": "model reasoning", - "tool_calls": [{ - "id": "call-1", - "type": "function", - "function": { - "name": "lookup", - "arguments": { "query": "openhuman" } - } - }] - } - }], - "openhuman": { - "usage": { - "input_tokens": 11, - "output_tokens": 13, - "cached_input_tokens": 5 - }, - "billing": { "charged_amount_usd": 0.0123 } - } - })) - .into_response() -} - -async fn provider_responses( - State(state): State, - Json(body): Json, -) -> Response { - state - .response_requests - .lock() - .expect("response requests") - .push(body); - Json(json!({ - "output_text": "responses fallback answer", - "output": [] - })) - .into_response() -} - -async fn serve_composio_mock() -> (String, ComposioMockState) { - let state = ComposioMockState::default(); - let app = Router::new() - .route( - "/agent-integrations/composio/toolkits", - get(composio_toolkits), - ) - .route("/agent-integrations/composio/tools", get(composio_tools)) - .route( - "/agent-integrations/composio/authorize", - post(composio_authorize), - ) - .route( - "/agent-integrations/composio/connections/{id}", - delete(composio_delete_connection), - ) - .route( - "/agent-integrations/composio/triggers/available", - get(composio_available_triggers), - ) - .with_state(state.clone()); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("bind composio mock"); - let addr = listener.local_addr().expect("composio mock addr"); - tokio::spawn(async move { - axum::serve(listener, app) - .await - .expect("composio mock serve"); - }); - (format!("http://{addr}"), state) -} - -async fn composio_toolkits(State(state): State, headers: HeaderMap) -> Response { - record_composio( - &state, - "GET", - "/agent-integrations/composio/toolkits", - None, - &headers, - ); - Json(json!({ "success": true, "data": { "toolkits": ["gmail", "github"] } })).into_response() -} - -async fn composio_tools( - State(state): State, - headers: HeaderMap, - uri: axum::http::Uri, -) -> Response { - record_composio( - &state, - "GET", - uri.path_and_query().unwrap().as_str(), - None, - &headers, - ); - Json(json!({ - "success": true, - "data": { - "tools": [{ - "type": "function", - "function": { - "name": "GMAIL_SEND_EMAIL", - "description": "Send email", - "parameters": { "type": "object" } - } - }] - } - })) - .into_response() -} - -async fn composio_authorize( - State(state): State, - headers: HeaderMap, - Json(body): Json, -) -> Response { - record_composio( - &state, - "POST", - "/agent-integrations/composio/authorize", - Some(body), - &headers, - ); - Json(json!({ - "success": true, - "data": { - "connectUrl": "https://example.test/connect", - "connectionId": "conn_123" - } - })) - .into_response() -} - -async fn composio_delete_connection( - State(state): State, - headers: HeaderMap, - axum::extract::Path(id): axum::extract::Path, -) -> Response { - record_composio( - &state, - "DELETE", - &format!("/agent-integrations/composio/connections/{id}"), - None, - &headers, - ); - Json(json!({ - "success": true, - "data": { "deleted": true, "memory_chunks_deleted": 2 } - })) - .into_response() -} - -async fn composio_available_triggers( - State(state): State, - headers: HeaderMap, - uri: axum::http::Uri, -) -> Response { - record_composio( - &state, - "GET", - uri.path_and_query().unwrap().as_str(), - None, - &headers, - ); - Json(json!({ - "success": true, - "data": { - "triggers": [{ - "slug": "GMAIL_NEW_GMAIL_MESSAGE", - "scope": "static", - "defaultConfig": { "labelIds": ["INBOX"] }, - "requiredConfigKeys": ["labelIds"] - }] - } - })) - .into_response() -} - -fn record_composio( - state: &ComposioMockState, - method: &str, - path: &str, - body: Option, - headers: &HeaderMap, -) { - state.requests.lock().expect("composio requests").push(( - method.to_string(), - path.to_string(), - body, - header(headers, "authorization"), - )); -} - -fn header(headers: &HeaderMap, name: &str) -> Option { - headers - .get(name) - .and_then(|value| value.to_str().ok()) - .map(ToString::to_string) -} - -fn owned_domain_config(workspace_root: &std::path::Path) -> Config { - let mut config = Config::default(); - config.workspace_dir = workspace_root.join("workspace"); - config.config_path = workspace_root.join("config.toml"); - std::fs::create_dir_all(&config.workspace_dir).expect("workspace dir"); - config -} - -#[test] -fn tool_registry_public_apis_cover_entries_diagnostics_and_provider_policy() { - crate::tinyhumans_boot::boot(); - let dir = tempdir().expect("tempdir"); - let mut config = owned_domain_config(dir.path()); - config.mcp_client.enabled = true; - config.mcp_client.servers = vec![ - McpServerConfig { - server: tinymcp_bus::McpServerConfig { - name: "filesystem".to_string(), - enabled: true, - allowed_tools: vec!["read_file".to_string(), "write_file".to_string()], - disallowed_tools: vec!["delete_file".to_string()], - ..Default::default() - }, - ..Default::default() - }, - McpServerConfig { - server: tinymcp_bus::McpServerConfig { - name: "disabled".to_string(), - enabled: false, - ..Default::default() - }, - ..Default::default() - }, - ]; - config.capability_providers = vec![ - CapabilityProviderConfig { - id: " Acme Tools ".to_string(), - display_name: " Acme Tooling ".to_string(), - source_uri: Some(" https://example.test/acme.json ".to_string()), - source_digest: Some(" sha256:abc ".to_string()), - trust_state: CapabilityProviderTrustState::Trusted, - enabled: true, - }, - CapabilityProviderConfig { - id: "zeta.provider".to_string(), - display_name: " ".to_string(), - source_uri: Some(" ".to_string()), - source_digest: None, - trust_state: CapabilityProviderTrustState::Untrusted, - enabled: false, - }, - ]; - - assert_eq!( - normalize_capability_provider_id(" Acme Tools "), - Ok("acme-tools".to_string()) - ); - assert!(normalize_capability_provider_id(" ").is_err()); - assert!(normalize_capability_provider_id(&"x".repeat(120)).is_err()); - - let providers = list_capability_providers(&config).expect("providers"); - assert_eq!( - providers - .iter() - .map(|provider| provider.id.as_str()) - .collect::>(), - vec!["acme-tools", "zeta.provider"] - ); - assert_eq!(providers[0].display_name, "Acme Tooling"); - assert_eq!( - providers[0].source_uri.as_deref(), - Some("https://example.test/acme.json") - ); - assert_eq!(providers[1].display_name, "zeta.provider"); - assert!(providers[1].source_uri.is_none()); - - let acme = capability_provider_by_id(&config, " acme tools ") - .expect("provider lookup") - .expect("acme provider"); - assert_eq!(acme.id, "acme-tools"); - assert!(is_capability_provider_trusted_enabled( - &config, - "ACME TOOLS" - )); - assert!(!is_capability_provider_trusted_enabled( - &config, - "zeta.provider" - )); - assert!(capability_provider_by_id(&config, "missing") - .expect("missing provider lookup") - .is_none()); - - let diagnostics = tool_registry_ops::diagnostics_for_config(&config).value; - assert!(diagnostics.total_tools > 0); - assert!(diagnostics.enabled_tools > 0); - assert!(diagnostics.json_rpc_tools > 0); - assert!(diagnostics - .possible_write_surfaces - .iter() - .any(|tool_id| tool_id.contains("execute") || tool_id.contains("write"))); - assert!(diagnostics - .policy_surfaces - .iter() - .any(|tool_id| tool_id == "tool_registry.diagnostics")); - assert_eq!(diagnostics.mcp_allowlists.server_count, 2); - assert_eq!(diagnostics.mcp_allowlists.enabled_server_count, 1); - assert!(diagnostics.mcp_allowlists.servers[0].has_allowlist); - assert!(diagnostics.mcp_allowlists.servers[0].has_denylist); - assert_eq!(diagnostics.capability_providers.total_providers, 2); - assert_eq!(diagnostics.capability_providers.enabled_providers, 1); - assert_eq!( - diagnostics.capability_providers.trusted_enabled_providers, - 1 - ); - - let mut duplicate_config = owned_domain_config(dir.path()); - duplicate_config.capability_providers = vec![ - CapabilityProviderConfig { - id: "Acme Tools".to_string(), - ..CapabilityProviderConfig::default() - }, - CapabilityProviderConfig { - id: "acme-tools".to_string(), - ..CapabilityProviderConfig::default() - }, - ]; - let duplicate_diagnostics = capability_provider_diagnostics(&duplicate_config); - assert_eq!(duplicate_diagnostics.total_providers, 2); - assert!(duplicate_diagnostics.registry_errors[0].contains("duplicate")); - - tool_registry_denials::record( - "tools.write_file", - "approval_required", - "write", - "medium risk", - ); - let denials = tool_registry_denials::list(1); - assert_eq!(denials.len(), 1); - assert_eq!(denials[0].tool_name, "tools.write_file"); - tool_registry_denials::record("", "policy", "blocked", "ignored"); - tool_registry_denials::record(" tools.blank ", "", "", ""); - tool_registry_denials::record("tools.secret", "policy", "blocked", "Bearer secret"); - tool_registry_denials::record("tools.long", "policy", "blocked", &"a".repeat(500)); - let recent_denials = tool_registry_denials::list(4); - assert_eq!(recent_denials[0].tool_name, "tools.long"); - assert_eq!(recent_denials[0].reason.chars().count(), 241); - assert_eq!(recent_denials[1].reason, "[redacted: sensitive content]"); - assert_eq!(recent_denials[2].policy, "unknown"); - assert_eq!(recent_denials[2].action, "blocked"); - assert_eq!(recent_denials[2].reason, ""); - - let registry = list_tools().value.tools; - assert!(registry.iter().any(|entry| { - entry.tool_id == "tools.web_search" - && entry.tags.iter().any(|tag| tag == "retrieval") - && entry.route.pointer("/protocol").and_then(Value::as_str) == Some("json_rpc") - })); - assert!(registry.iter().any(|entry| { - entry.tool_id.contains("memory") && entry.tags.iter().any(|tag| tag == "memory") - })); - - let web_search = get_tool(" tools.web_search ") - .expect("get web search") - .value; - assert_eq!(web_search.title, "Web Search"); - assert_eq!( - web_search - .input_schema - .pointer("/additionalProperties") - .and_then(Value::as_bool), - Some(false) - ); - assert!(get_tool(" ") - .expect_err("blank tool id") - .contains("tool_id")); - assert!(get_tool("missing.tool") - .expect_err("missing tool") - .contains("tool not found")); -} - -#[tokio::test] -async fn tool_registry_controller_handlers_cover_list_get_and_validation_paths() { - crate::tinyhumans_boot::boot(); - let schemas = all_tool_registry_controller_schemas(); - assert_eq!( - schemas - .iter() - .map(|schema| schema.function) - .collect::>(), - vec!["list", "get", "diagnostics"] - ); - - let controllers = all_tool_registry_registered_controllers(); - assert_eq!(controllers.len(), 3); - - let list_handler = controllers - .iter() - .find(|controller| controller.schema.function == "list") - .expect("list controller") - .handler; - let list_value = list_handler(Map::new()).await.expect("list value"); - assert!(list_value - .get("tools") - .and_then(Value::as_array) - .is_some_and(|tools| !tools.is_empty())); - - let get_handler = controllers - .iter() - .find(|controller| controller.schema.function == "get") - .expect("get controller") - .handler; - let mut params = Map::new(); - params.insert("tool_id".to_string(), json!("tools.web_search")); - let get_value = get_handler(params).await.expect("get value"); - assert_eq!( - get_value.get("tool_id").and_then(Value::as_str), - Some("tools.web_search") - ); - - let mut blank_params = Map::new(); - blank_params.insert("tool_id".to_string(), json!(" ")); - assert!(get_handler(blank_params) - .await - .expect_err("blank tool id") - .contains("non-empty string")); - - let mut typed_params = Map::new(); - typed_params.insert("tool_id".to_string(), json!(42)); - assert!(get_handler(typed_params) - .await - .expect_err("numeric tool id") - .contains("non-empty string")); - - let diagnostics_handler = controllers - .iter() - .find(|controller| controller.schema.function == "diagnostics") - .expect("diagnostics controller") - .handler; - let dir = tempdir().expect("tempdir"); - let previous_workspace = { - let _env_guard = OWNED_DOMAIN_ENV_LOCK - .get_or_init(|| Mutex::new(())) - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - let previous_workspace = std::env::var_os("OPENHUMAN_WORKSPACE"); - std::env::set_var("OPENHUMAN_WORKSPACE", dir.path()); - previous_workspace - }; - let diagnostics_value = diagnostics_handler(Map::new()) - .await - .expect("diagnostics value"); - { - let _env_guard = OWNED_DOMAIN_ENV_LOCK - .get_or_init(|| Mutex::new(())) - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - match previous_workspace { - Some(value) => std::env::set_var("OPENHUMAN_WORKSPACE", value), - None => std::env::remove_var("OPENHUMAN_WORKSPACE"), - } - } - assert!(diagnostics_value - .get("total_tools") - .or_else(|| diagnostics_value.pointer("/diagnostics/total_tools")) - .and_then(Value::as_u64) - .is_some_and(|count| count > 0)); -} diff --git a/tests/raw_coverage/session_store_e2e.rs b/tests/raw_coverage/session_store_e2e.rs index 02457c53275..3548f4bf871 100644 --- a/tests/raw_coverage/session_store_e2e.rs +++ b/tests/raw_coverage/session_store_e2e.rs @@ -883,94 +883,6 @@ async fn ai_artifacts_list_filter_get_and_delete() { harness.join.abort(); } -/// Failure paths for the artifact surface: a traversal id is refused before -/// any filesystem access, an absent id is an error, and `regenerate` refuses -/// both a non-presentation artifact and a call with no routing context. -#[tokio::test] -async fn ai_artifacts_reject_traversal_absence_and_unregenerable_kinds() { - let _lock = env_lock(); - let harness = setup().await; - - seed_artifact( - &harness.workspace, - "artifact-doc", - "document", - "A document", - "2026-03-01T00:00:00Z", - None, - ); - - let traversal = rpc( - &harness.rpc_base, - 33_101, - "openhuman.ai_get_artifact", - json!({ "artifact_id": "../../etc/passwd" }), - ) - .await; - assert!( - error_message(&traversal, "ai_get_artifact traversal").contains("must not contain '/'"), - "an id with a path separator must be refused by the validator: {traversal}" - ); - - let empty = rpc( - &harness.rpc_base, - 33_102, - "openhuman.ai_delete_artifact", - json!({ "artifact_id": " " }), - ) - .await; - assert!( - error_message(&empty, "ai_delete_artifact blank id").contains("must not be empty"), - "a whitespace-only id trims to empty and must be refused: {empty}" - ); - - let missing = rpc( - &harness.rpc_base, - 33_103, - "openhuman.ai_get_artifact", - json!({ "artifact_id": "artifact-that-does-not-exist" }), - ) - .await; - assert!( - error_message(&missing, "ai_get_artifact absent").contains("artifact-that-does-not-exist"), - "the error must identify the artifact: {missing}" - ); - - // regenerate needs routing context for the socket events it triggers. - let no_routing = rpc( - &harness.rpc_base, - 33_104, - "openhuman.ai_regenerate", - json!({ "artifact_id": "artifact-doc", "thread_id": "", "client_id": "" }), - ) - .await; - assert!( - error_message(&no_routing, "ai_regenerate without routing") - .contains("thread_id + client_id"), - "regenerate must refuse without event routing: {no_routing}" - ); - - // Only presentations persist the args a re-dispatch needs. - let wrong_kind = rpc( - &harness.rpc_base, - 33_105, - "openhuman.ai_regenerate", - json!({ - "artifact_id": "artifact-doc", - "thread_id": "thread-alpha", - "client_id": "client-1", - }), - ) - .await; - let message = error_message(&wrong_kind, "ai_regenerate on a document"); - assert!( - message.contains("only supported for presentations") && message.contains("document"), - "the refusal must name the rule and the actual kind, got: {message}" - ); - - harness.join.abort(); -} - // ── test_support ────────────────────────────────────────────────────────── /// The `test_support.*` controllers are compiled in only under diff --git a/tests/raw_coverage/skill_runtime_e2e.rs b/tests/raw_coverage/skill_runtime_e2e.rs deleted file mode 100644 index 1631201833e..00000000000 --- a/tests/raw_coverage/skill_runtime_e2e.rs +++ /dev/null @@ -1,1411 +0,0 @@ -#![cfg(any())] // TODO(#6382): migrate this legacy TinyAgents fixture to the hosted public API. - -//! JSON-RPC E2E coverage for the skill execution surface: `skill_runtime_*`, -//! the uncovered half of `skills_*`, `skill_registry_categories`, and the -//! `javascript_*` runtime bridge. -//! -//! Run: -//! `cargo test --test raw_coverage_all --features "$(bash scripts/ci/product-features.sh)" skill_runtime_e2e` -//! -//! ## Hermetic by construction -//! -//! Three fixtures, no network out: -//! -//! * A **planted skill** at `/skills//{SKILL.md,skill.toml}`. -//! That directory is the legacy skill root — `discover_filtered` scans it with -//! no trust marker required (`ops_discover.rs:250-261`), which makes it the -//! cheapest honest way to give the registry something real to resolve. -//! * **Planted run logs** in `/skills/.runs/`, written in the exact -//! `write_header` / `write_footer` format (`run_log.rs:146-172`, `:598-612`). -//! `scan_runs` and `read_run_log_slice` parse those files, so a planted log is -//! precisely what the code under test consumes. -//! * A **loopback fixture catalog** for `skill_registry_categories` and the -//! `skills_install_from_url` happy path, reached through the existing -//! `OPENHUMAN_SKILL_REGISTRY_CATALOG_URL` / -//! `OPENHUMAN_SKILL_INSTALL_ALLOW_LOCAL_HTTP` escape hatches. -//! -//! ## Why the live `run` arc is asserted at its validation boundary, not end to end -//! -//! `spawn_workflow_run_background` validates the skill id and its required -//! inputs **synchronously**, then `tokio::spawn`s a detached orchestrator that -//! writes the run-log header, calls `Config::load_or_init()` (reading -//! process-global env), and drives a real agent turn -//! (`run_machinery.rs:184-230`). Driving that here would (a) race the header -//! write that a following `read_run_log` needs, and (b) leave a detached task -//! reading `HOME` / `OPENHUMAN_WORKSPACE` after this case has released the env -//! lock — which, now that all ~77 suites share one process, is contamination -//! aimed at every other suite in the binary. So `run` is asserted on the two -//! errors it raises before spawning, and the log-reading methods are asserted -//! against planted logs where the content is knowable. - -use std::net::SocketAddr; -use std::path::{Path, PathBuf}; -use std::sync::{Mutex, OnceLock}; -use std::time::Duration; - -use axum::http::header::AUTHORIZATION; -use axum::routing::get; -use axum::Router; -use serde_json::{json, Value}; -use tempfile::{tempdir, TempDir}; - -use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR}; -use openhuman_rpc::server::build_core_http_router; - -/// The bearer this suite *proposes*. It is only used if this suite happens to -/// be the first in the aggregated binary to initialise the token subsystem — -/// see `rpc_token()` below, which is what actually gets sent. -const PROPOSED_RPC_TOKEN: &str = "skill-runtime-e2e-token"; - -static AUTH_INIT: OnceLock<()> = OnceLock::new(); - -/// The crate-wide env lock, not a private one — every `tests/raw_coverage/` -/// suite shares one process, so a file-local lock would isolate nothing. -static ENV_LOCK: &OnceLock> = &crate::SHARED_ENV_LOCK; - -fn env_lock() -> std::sync::MutexGuard<'static, ()> { - ENV_LOCK - .get_or_init(|| Mutex::new(())) - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) -} - -// ── Env plumbing ──────────────────────────────────────────────────────────── - -struct EnvVarGuard { - key: &'static str, - old: Option, -} - -impl EnvVarGuard { - fn set_to_path(key: &'static str, path: &Path) -> Self { - let old = std::env::var(key).ok(); - std::env::set_var(key, path.as_os_str()); - Self { key, old } - } - - fn set(key: &'static str, value: &str) -> Self { - let old = std::env::var(key).ok(); - std::env::set_var(key, value); - Self { key, old } - } - - fn unset(key: &'static str) -> Self { - let old = std::env::var(key).ok(); - std::env::remove_var(key); - Self { key, old } - } -} - -impl Drop for EnvVarGuard { - fn drop(&mut self) { - match &self.old { - Some(value) => std::env::set_var(self.key, value), - None => std::env::remove_var(self.key), - } - } -} - -/// The bearer the running process will actually validate. -/// -/// `core::auth::RPC_TOKEN` is a process-global `OnceLock` and `init_rpc_token` -/// returns early once it is set. Every `tests/raw_coverage/` suite now shares -/// one process, so the FIRST suite to initialise pins the token for all of -/// them; a suite that sent its own hard-coded literal would get 401 whenever it -/// lost that race, in an order that depends on libtest scheduling and load. -/// -/// So: propose a token, initialise, then ask what the process settled on and -/// send that. Correct whether this suite wins the race or loses it. -fn rpc_token() -> &'static str { - AUTH_INIT.get_or_init(|| { - if std::env::var(CORE_TOKEN_ENV_VAR) - .map(|v| v.trim().is_empty()) - .unwrap_or(true) - { - std::env::set_var(CORE_TOKEN_ENV_VAR, PROPOSED_RPC_TOKEN); - } - let token_dir = std::env::temp_dir().join("openhuman-skill-runtime-e2e-auth"); - std::fs::create_dir_all(&token_dir).expect("token dir"); - init_rpc_token(&token_dir).expect("init rpc auth token"); - }); - openhuman_core::core::auth::get_rpc_token() - .expect("the token subsystem is initialised by the line above") -} - -// ── Harness ───────────────────────────────────────────────────────────────── - -const MIN_CONFIG: &str = r#"api_url = "http://127.0.0.1:9" -default_model = "skill-runtime-e2e-model" - -[secrets] -encrypt = false - -[local_ai] -enabled = false - -[memory] -provider = "none" -embedding_provider = "none" -embedding_model = "none" -embedding_dimensions = 0 - -[memory_tree] -embedding_strict = false -"#; - -struct Harness { - _tmp: TempDir, - _guards: Vec, - workspace: PathBuf, - rpc_base: String, - join: tokio::task::JoinHandle>, -} - -async fn setup(extra: Vec) -> Harness { - let _ = rpc_token(); - - let tmp = tempdir().expect("tempdir"); - let home = tmp.path(); - let openhuman_home = home.join(".openhuman"); - std::fs::create_dir_all(&openhuman_home).expect("create .openhuman"); - std::fs::write(openhuman_home.join("config.toml"), MIN_CONFIG).expect("write config.toml"); - let _: openhuman_core::config::Config = - toml::from_str(MIN_CONFIG).expect("test config must match the config schema"); - - let workspace = home.join("workspace"); - std::fs::create_dir_all(workspace.join("skills")).expect("create workspace skills dir"); - // Inside the workspace on purpose. `file_read` resolves relative paths - // against `action_dir`, but `SecurityPolicy` jails the resolved path to - // `workspace_dir` — an action dir outside the workspace makes every read - // fail with `[policy-blocked] Resolved path escapes workspace`, which is - // exactly what the first run of this suite hit. The tool's own description - // ("your working directory (the action sandbox)") does not mention the - // second, tighter boundary. - let action_dir = workspace.join("actions"); - std::fs::create_dir_all(&action_dir).expect("create action dir"); - - let mut guards = vec![ - EnvVarGuard::set_to_path("HOME", home), - EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", &workspace), - EnvVarGuard::set_to_path("OPENHUMAN_ACTION_DIR", &action_dir), - EnvVarGuard::unset("BACKEND_URL"), - EnvVarGuard::unset("VITE_BACKEND_URL"), - EnvVarGuard::unset("OPENHUMAN_API_URL"), - EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "file"), - ]; - guards.extend(extra); - - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("bind rpc listener"); - let addr: SocketAddr = listener.local_addr().expect("rpc listener addr"); - let router = build_core_http_router(false); - let join = tokio::spawn(async move { axum::serve(listener, router).await }); - - Harness { - _tmp: tmp, - _guards: guards, - workspace, - rpc_base: format!("http://{addr}"), - join, - } -} - -async fn rpc(base: &str, id: i64, method: &str, params: Value) -> Value { - let client = reqwest::Client::builder() - .timeout(Duration::from_secs(120)) - .build() - .expect("build client"); - let url = format!("{}/rpc", base.trim_end_matches('/')); - let response = client - .post(&url) - .header(AUTHORIZATION, format!("Bearer {}", rpc_token())) - .json(&json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params })) - .send() - .await - .unwrap_or_else(|err| panic!("POST {url} {method}: {err}")); - assert!( - response.status().is_success(), - "HTTP {} for {method}", - response.status() - ); - response - .json::() - .await - .unwrap_or_else(|err| panic!("json for {method}: {err}")) -} - -fn ok<'a>(value: &'a Value, context: &str) -> &'a Value { - if let Some(error) = value.get("error") { - panic!("{context}: unexpected JSON-RPC error: {error}"); - } - value - .get("result") - .unwrap_or_else(|| panic!("{context}: missing result: {value}")) -} - -/// The controller payload, unwrapping the `{result, logs}` envelope when one -/// is present. -/// -/// `Outcome::into_cli_compatible_json` (`crates/openhuman-rpc/src/mod.rs:54-62`) wraps the -/// value in `{result, logs}` **only when the handler emitted at least one log -/// line**, and returns it bare otherwise. So the response shape of a single -/// namespace varies with whether its handler happened to log — `javascript_*` -/// always logs and is always wrapped; the `skills_*` handlers pass -/// `Vec::new()` and never are. A caller cannot write one parser for the RPC -/// surface without knowing that. See -/// `~/tinyhuman/bugs/e2e-wave-rpc-envelope-shape-varies-with-logging.md`. -fn payload<'a>(value: &'a Value, context: &str) -> &'a Value { - let result = ok(value, context); - match (result.get("result"), result.get("logs")) { - (Some(inner), Some(_)) => inner, - _ => result, - } -} - -fn error_message<'a>(value: &'a Value, context: &str) -> &'a str { - value - .get("error") - .unwrap_or_else(|| panic!("{context}: expected a JSON-RPC error, got: {value}")) - .get("message") - .and_then(Value::as_str) - .unwrap_or_else(|| panic!("{context}: error carries no message: {value}")) -} - -// ── Fixtures ──────────────────────────────────────────────────────────────── - -/// Plant a runnable skill under the legacy `/skills/` root. -/// -/// `skill.toml` supplies the runnable id and the declared `[[inputs]]`; -/// `SKILL.md` supplies the body that becomes the inline system prompt. The -/// resource file is what `skills_read_resource` reads back. -fn plant_skill(workspace: &Path, slug: &str, required_input: &str) -> PathBuf { - let dir = workspace.join("skills").join(slug); - std::fs::create_dir_all(dir.join("references")).expect("create skill dir"); - std::fs::write( - dir.join("SKILL.md"), - format!( - "---\nname: {slug}\ndescription: A planted skill for the skill-runtime e2e suite.\n---\n\n\ - # {slug}\n\nDo the planted thing.\n" - ), - ) - .expect("write SKILL.md"); - std::fs::write( - dir.join("skill.toml"), - format!( - "id = \"{slug}\"\nwhen_to_use = \"When the e2e suite says so.\"\n\n\ - [[inputs]]\nname = \"{required_input}\"\ndescription = \"The one input this skill insists on.\"\n\ - required = true\ntype = \"string\"\n" - ), - ) - .expect("write skill.toml"); - std::fs::write( - dir.join("references").join("note.md"), - "PLANTED_RESOURCE_BODY\n", - ) - .expect("write resource"); - dir -} - -/// Write a run log in the on-disk format `write_header` / `write_footer` -/// produce, so `scan_runs` / `read_run_log_slice` parse it exactly as they -/// would a real run's. -/// -/// `finished` controls whether the `--- result ---` footer lands, which is the -/// single bit that separates a `RUNNING` run from a terminal one and drives the -/// `complete` flag the frontend polls on. -fn plant_run_log( - workspace: &Path, - workflow_id: &str, - run_id: &str, - started_rfc3339: &str, - finished: Option<(&str, u64, &str)>, -) -> PathBuf { - let runs = workspace.join("skills").join(".runs"); - std::fs::create_dir_all(&runs).expect("create runs dir"); - let short = run_id.get(..8).unwrap_or(run_id); - let path = runs.join(format!("{workflow_id}_20260907T101010Z_{short}.log")); - - let mut body = format!( - "==== workflow_run: {workflow_id} ====\n\ - run_id : {run_id}\n\ - started: {started_rfc3339} UTC\n\ - inputs : {{}}\n\n\ - --- task prompt ---\nplanted prompt\n\n\ - --- steps ---\n" - ); - if let Some((status, duration_ms, output)) = finished { - body.push_str(&format!( - "\n--- result ---\n\ - status : {status}\n\ - duration: {duration_ms} ms\n\ - finished: 2026-09-07T10:20:10+00:00 UTC\n\n{output}\n" - )); - } - std::fs::write(&path, body).expect("write run log"); - path -} - -/// A loopback stand-in for the skill catalog + a downloadable `SKILL.md`. -async fn serve_fixture_catalog() -> ( - SocketAddr, - tokio::task::JoinHandle>, -) { - async fn catalog() -> axum::Json { - axum::Json(json!([ - { - "name": "planted-git-helper", - "description": "Automate git triage.", - "category": "software-development", - "source": "fixture", - "tags": ["git"], - "platforms": ["linux", "macos"], - "envVars": [], - "commands": [] - }, - { - "name": "planted-notes-helper", - "description": "Summarize notes.", - "category": "productivity", - "source": "fixture", - "tags": ["notes"], - "platforms": ["linux", "macos"], - "envVars": [], - "commands": [] - }, - { - // Deliberately category-less: `list_categories` filters empty - // strings out, so this row must NOT contribute a category. - "name": "planted-uncategorised", - "description": "No category at all.", - "category": "", - "source": "fixture", - "tags": [], - "platforms": ["linux", "macos"], - "envVars": [], - "commands": [] - } - ])) - } - - async fn skill_md() -> &'static str { - "---\nname: url-installed-skill\ndescription: Installed over loopback HTTP by the e2e suite.\n---\n\n# URL Installed Skill\n\nBody.\n" - } - - let app = Router::new() - .route("/skills.json", get(catalog)) - .route("/skills/url-installed-skill/SKILL.md", get(skill_md)); - - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("bind fixture listener"); - let addr = listener.local_addr().expect("fixture addr"); - let join = tokio::spawn(async move { axum::serve(listener, app).await }); - (addr, join) -} - -// ── skill_runtime ─────────────────────────────────────────────────────────── - -/// `skill_runtime_schemas` and `skill_runtime_resolve_runtimes` — the two -/// methods the production smoke-script generator reads. -/// -/// `schemas` must return the namespace's own six controllers with the right -/// namespace stamped on each; a generator fed a truncated or mis-namespaced -/// list emits scripts that call methods that do not exist. -#[tokio::test] -async fn skill_runtime_schemas_and_runtime_resolution() { - let _lock = env_lock(); - let harness = setup(Vec::new()).await; - - let schemas = rpc( - &harness.rpc_base, - 100, - "openhuman.skill_runtime_schemas", - json!({}), - ) - .await; - let schemas = ok(&schemas, "skill_runtime_schemas"); - let listed = schemas - .get("schemas") - .and_then(Value::as_array) - .unwrap_or_else(|| panic!("schemas payload has no `schemas` array: {schemas}")); - - let functions: Vec<&str> = listed - .iter() - .map(|entry| { - assert_eq!( - entry.get("namespace").and_then(Value::as_str), - Some("skill_runtime"), - "every returned schema must be stamped with its own namespace: {entry}" - ); - entry - .get("function") - .and_then(Value::as_str) - .unwrap_or_else(|| panic!("schema entry without a `function`: {entry}")) - }) - .collect(); - - for expected in [ - "run", - "cancel", - "recent_runs", - "read_run_log", - "resolve_runtimes", - "schemas", - ] { - assert!( - functions.contains(&expected), - "skill_runtime_schemas must advertise `{expected}`, got {functions:?}" - ); - } - assert_eq!( - functions.len(), - 6, - "the namespace has exactly six controllers; got {functions:?}" - ); - - // `resolve_runtimes` scoped to one runtime must return exactly that one, - // with the documented status fields present. Availability depends on the - // host toolchain, so the assertion is on shape and scoping, not on a - // machine-specific `available: true`. - let node_only = rpc( - &harness.rpc_base, - 101, - "openhuman.skill_runtime_resolve_runtimes", - json!({ "runtime": "node" }), - ) - .await; - let node_only = ok(&node_only, "skill_runtime_resolve_runtimes node"); - let runtimes = node_only - .get("runtimes") - .and_then(Value::as_array) - .unwrap_or_else(|| panic!("resolve_runtimes has no `runtimes` array: {node_only}")); - assert_eq!( - runtimes.len(), - 1, - "scoping to `node` must resolve only node: {node_only}" - ); - assert_eq!( - runtimes[0].get("runtime").and_then(Value::as_str), - Some("node"), - "the single entry must be the node runtime: {node_only}" - ); - for field in ["enabled", "available"] { - assert!( - runtimes[0].get(field).is_some_and(Value::is_boolean), - "`{field}` must be present and boolean: {node_only}" - ); - } - - // The default (`all`) resolves both slots. - let all = rpc( - &harness.rpc_base, - 102, - "openhuman.skill_runtime_resolve_runtimes", - json!({}), - ) - .await; - let all_names: Vec<&str> = ok(&all, "skill_runtime_resolve_runtimes all") - .get("runtimes") - .and_then(Value::as_array) - .expect("runtimes array") - .iter() - .filter_map(|r| r.get("runtime").and_then(Value::as_str)) - .collect(); - assert!( - all_names.contains(&"node") && all_names.contains(&"python"), - "the default must resolve both runtimes, got {all_names:?}" - ); - - // Failure path: an unrecognised runtime is refused, and the error names the - // three that are accepted rather than failing opaquely. - let bogus = rpc( - &harness.rpc_base, - 103, - "openhuman.skill_runtime_resolve_runtimes", - json!({ "runtime": "brainfuck" }), - ) - .await; - let message = error_message(&bogus, "skill_runtime_resolve_runtimes bogus"); - assert!( - message.contains("brainfuck") && message.contains("node") && message.contains("python"), - "the refusal must name the bad value and the accepted ones, got: {message}" - ); - - harness.join.abort(); -} - -/// `skill_runtime_run`'s two synchronous refusals, then `recent_runs`, -/// `read_run_log` and `cancel` against planted logs. -#[tokio::test] -async fn skill_runtime_run_validation_and_run_log_surface() { - let _lock = env_lock(); - let harness = setup(Vec::new()).await; - plant_skill(&harness.workspace, "planted-runtime-skill", "target_repo"); - - // Refusal 1: an id no root resolves. - let unknown = rpc( - &harness.rpc_base, - 110, - "openhuman.skill_runtime_run", - json!({ "skill_id": "no-such-skill-anywhere" }), - ) - .await; - let message = error_message(&unknown, "skill_runtime_run unknown skill"); - assert!( - message.contains("unknown skill") && message.contains("no-such-skill-anywhere"), - "the refusal must name the unresolved skill, got: {message}" - ); - - // Refusal 2: the skill resolves, but a declared `required` input is absent. - // This is the assertion that proves the planted skill's `skill.toml` was - // actually parsed — a fallback SKILL.md-only definition declares no inputs - // and would have started a run instead. - let missing_input = rpc( - &harness.rpc_base, - 111, - "openhuman.skill_runtime_run", - json!({ "skill_id": "planted-runtime-skill" }), - ) - .await; - let message = error_message(&missing_input, "skill_runtime_run missing input"); - assert!( - message.contains("missing required inputs") && message.contains("target_repo"), - "the refusal must name the missing input, got: {message}" - ); - - // An explicit null is treated as absent, not as a supplied value. - let null_input = rpc( - &harness.rpc_base, - 112, - "openhuman.skill_runtime_run", - json!({ "skill_id": "planted-runtime-skill", "inputs": { "target_repo": null } }), - ) - .await; - assert!( - error_message(&null_input, "skill_runtime_run null input").contains("target_repo"), - "a null input must count as missing: {null_input}" - ); - - // ── the run-log surface, against logs whose content is knowable ────────── - let running_id = "aaaaaaaa-1111-2222-3333-444444444444"; - let done_id = "bbbbbbbb-1111-2222-3333-444444444444"; - plant_run_log( - &harness.workspace, - "planted-runtime-skill", - running_id, - "2026-09-07T10:10:10+00:00", - None, - ); - plant_run_log( - &harness.workspace, - "planted-runtime-skill", - done_id, - "2026-09-07T11:10:10+00:00", - Some(("DONE", 4242, "PLANTED_RUN_OUTPUT")), - ); - // A third run, under a different skill, to prove the filter bites. - plant_run_log( - &harness.workspace, - "some-other-skill", - "cccccccc-1111-2222-3333-444444444444", - "2026-09-07T12:10:10+00:00", - Some(("FAILED", 7, "nope")), - ); - - let recent = rpc( - &harness.rpc_base, - 113, - "openhuman.skill_runtime_recent_runs", - json!({}), - ) - .await; - let recent = ok(&recent, "skill_runtime_recent_runs"); - let runs = recent - .get("runs") - .and_then(Value::as_array) - .unwrap_or_else(|| panic!("recent_runs has no `runs` array: {recent}")); - assert_eq!( - runs.len(), - 3, - "all three planted runs must be seen: {recent}" - ); - // Sorted most-recent-first by `started`. - assert_eq!( - runs.iter() - .filter_map(|r| r.get("workflow_id").and_then(Value::as_str)) - .collect::>(), - vec![ - "some-other-skill", - "planted-runtime-skill", - "planted-runtime-skill" - ], - "runs must come back newest-first by `started`: {recent}" - ); - - // The unfinished log has no footer, so its status is the RUNNING default - // and it carries no duration; the finished one carries both. - let by_id = |id: &str| -> Value { - runs.iter() - .find(|r| r.get("run_id").and_then(Value::as_str) == Some(id)) - .unwrap_or_else(|| panic!("run {id} missing from {recent}")) - .clone() - }; - let running = by_id(running_id); - assert_eq!( - running.get("status").and_then(Value::as_str), - Some("RUNNING"), - "a log with no `--- result ---` footer must read as RUNNING: {running}" - ); - assert!( - running.get("duration_ms").is_none_or(Value::is_null), - "an unfinished run must not report a duration: {running}" - ); - let done = by_id(done_id); - assert_eq!( - done.get("status").and_then(Value::as_str), - Some("DONE"), - "the footer's status word must be parsed out: {done}" - ); - assert_eq!( - done.get("duration_ms").and_then(Value::as_u64), - Some(4242), - "the footer's `duration: ms` must be parsed to a number: {done}" - ); - - // Filtering scopes to one skill. - let filtered = rpc( - &harness.rpc_base, - 114, - "openhuman.skill_runtime_recent_runs", - json!({ "skill_id": "some-other-skill" }), - ) - .await; - let filtered = ok(&filtered, "skill_runtime_recent_runs filtered"); - let filtered_runs = filtered - .get("runs") - .and_then(Value::as_array) - .expect("runs"); - assert_eq!( - filtered_runs.len(), - 1, - "the skill_id filter must exclude the other two: {filtered}" - ); - assert_eq!( - filtered_runs[0].get("workflow_id").and_then(Value::as_str), - Some("some-other-skill") - ); - - // `limit` is honoured and clamped. - let limited = rpc( - &harness.rpc_base, - 115, - "openhuman.skill_runtime_recent_runs", - json!({ "limit": 1 }), - ) - .await; - assert_eq!( - ok(&limited, "skill_runtime_recent_runs limit") - .get("runs") - .and_then(Value::as_array) - .map(Vec::len), - Some(1), - "limit must cap the result: {limited}" - ); - - // ── read_run_log ──────────────────────────────────────────────────────── - let slice = rpc( - &harness.rpc_base, - 116, - "openhuman.skill_runtime_read_run_log", - json!({ "run_id": done_id }), - ) - .await; - let slice = ok(&slice, "skill_runtime_read_run_log"); - let content = slice - .get("content") - .and_then(Value::as_str) - .unwrap_or_else(|| panic!("read_run_log has no `content`: {slice}")); - assert!( - content.contains("PLANTED_RUN_OUTPUT") && content.contains(done_id), - "the slice must contain the log's own body and run id: {content}" - ); - assert_eq!( - slice.get("eof").and_then(Value::as_bool), - Some(true), - "a default 64 KiB read of a tiny log reaches EOF: {slice}" - ); - assert_eq!( - slice.get("complete").and_then(Value::as_bool), - Some(true), - "a log carrying the footer must report complete: {slice}" - ); - let end_offset = slice - .get("offset") - .and_then(Value::as_u64) - .expect("offset cursor"); - assert_eq!( - slice.get("bytes_read").and_then(Value::as_u64), - Some(end_offset), - "reading from offset 0, the cursor must equal the bytes returned: {slice}" - ); - - // Tail-mode: re-issuing at the returned cursor yields nothing new but keeps - // reporting `complete`, which is what stops the frontend polling. - let tail = rpc( - &harness.rpc_base, - 117, - "openhuman.skill_runtime_read_run_log", - json!({ "run_id": done_id, "offset": end_offset }), - ) - .await; - let tail = ok(&tail, "skill_runtime_read_run_log tail"); - assert_eq!(tail.get("bytes_read").and_then(Value::as_u64), Some(0)); - assert_eq!(tail.get("content").and_then(Value::as_str), Some("")); - assert_eq!(tail.get("complete").and_then(Value::as_bool), Some(true)); - - // A still-running log reports `complete: false` — the polling frontend - // depends on that bit exactly. - let running_slice = rpc( - &harness.rpc_base, - 118, - "openhuman.skill_runtime_read_run_log", - json!({ "run_id": running_id }), - ) - .await; - assert_eq!( - ok(&running_slice, "read_run_log running") - .get("complete") - .and_then(Value::as_bool), - Some(false), - "a footer-less log must not claim completion: {running_slice}" - ); - - // Failure path: an unknown run id resolves to no path and is refused. - let unknown_run = rpc( - &harness.rpc_base, - 119, - "openhuman.skill_runtime_read_run_log", - json!({ "run_id": "ffffffff-0000-0000-0000-000000000000" }), - ) - .await; - let message = error_message(&unknown_run, "read_run_log unknown run"); - assert!( - message.contains("unknown run_id"), - "the refusal must say the run id is unknown, got: {message}" - ); - - // ── cancel ────────────────────────────────────────────────────────────── - // No live run holds a cancellation token, so this is the documented - // "already finished or never existed" answer: reported, not thrown. - let cancel = rpc( - &harness.rpc_base, - 120, - "openhuman.skill_runtime_cancel", - json!({ "run_id": done_id }), - ) - .await; - let cancel = ok(&cancel, "skill_runtime_cancel"); - assert_eq!( - cancel.get("run_id").and_then(Value::as_str), - Some(done_id), - "cancel must echo the requested run id: {cancel}" - ); - assert_eq!( - cancel.get("cancelled").and_then(Value::as_bool), - Some(false), - "cancelling a run with no live token must report false, not error: {cancel}" - ); - - harness.join.abort(); -} - -// ── skills (the uncovered half) ───────────────────────────────────────────── - -/// `skills_run` / `skills_recent_runs` / `skills_read_run_log` / `skills_cancel` -/// — the older namespace over the same machinery, asserted at the points where -/// its wire shape differs from `skill_runtime_*`. -#[tokio::test] -async fn skills_run_and_log_surface_keeps_its_own_wire_shape() { - let _lock = env_lock(); - let harness = setup(Vec::new()).await; - plant_skill(&harness.workspace, "planted-legacy-skill", "ticket"); - - let unknown = rpc( - &harness.rpc_base, - 130, - "openhuman.skills_run", - json!({ "workflow_id": "not-a-skill" }), - ) - .await; - assert!( - error_message(&unknown, "skills_run unknown").contains("unknown skill"), - "skills_run must refuse an unresolved id: {unknown}" - ); - - // `skills_run` takes `workflow_id` where `skill_runtime_run` takes - // `skill_id`; sending the sibling's spelling is a params error, which is - // worth pinning because the two namespaces front the same machinery. - let wrong_param = rpc( - &harness.rpc_base, - 131, - "openhuman.skills_run", - json!({ "skill_id": "planted-legacy-skill" }), - ) - .await; - assert!( - error_message(&wrong_param, "skills_run wrong param").contains("workflow_id"), - "skills_run must name the param it wanted: {wrong_param}" - ); - - let missing_input = rpc( - &harness.rpc_base, - 132, - "openhuman.skills_run", - json!({ "workflow_id": "planted-legacy-skill" }), - ) - .await; - assert!( - error_message(&missing_input, "skills_run missing input").contains("ticket"), - "skills_run must name the missing required input: {missing_input}" - ); - - let run_id = "dddddddd-1111-2222-3333-444444444444"; - plant_run_log( - &harness.workspace, - "planted-legacy-skill", - run_id, - "2026-09-07T13:10:10+00:00", - Some(("DEGENERATE", 99, "PLANTED_LEGACY_OUTPUT")), - ); - - let recent = rpc( - &harness.rpc_base, - 133, - "openhuman.skills_recent_runs", - json!({ "workflow_id": "planted-legacy-skill" }), - ) - .await; - let recent = ok(&recent, "skills_recent_runs"); - let runs = recent - .get("runs") - .and_then(Value::as_array) - .unwrap_or_else(|| panic!("skills_recent_runs has no `runs`: {recent}")); - assert_eq!(runs.len(), 1, "one planted run for this skill: {recent}"); - assert_eq!( - runs[0].get("status").and_then(Value::as_str), - Some("DEGENERATE"), - "a DEGENERATE footer must survive the scan verbatim: {recent}" - ); - assert_eq!(runs[0].get("run_id").and_then(Value::as_str), Some(run_id)); - - let slice = rpc( - &harness.rpc_base, - 134, - "openhuman.skills_read_run_log", - json!({ "run_id": run_id, "max_bytes": 32 }), - ) - .await; - let slice = ok(&slice, "skills_read_run_log capped"); - assert_eq!( - slice.get("bytes_read").and_then(Value::as_u64), - Some(32), - "an explicit max_bytes must cap the slice at exactly that many bytes: {slice}" - ); - assert_eq!( - slice.get("eof").and_then(Value::as_bool), - Some(false), - "a capped read short of the file end must not claim EOF: {slice}" - ); - assert!( - slice - .get("content") - .and_then(Value::as_str) - .is_some_and(|c| c.starts_with("==== workflow_run:")), - "a read from offset 0 must start at the header banner: {slice}" - ); - - let cancel = rpc( - &harness.rpc_base, - 135, - "openhuman.skills_cancel", - json!({ "run_id": "not-a-live-run" }), - ) - .await; - let cancel = ok(&cancel, "skills_cancel"); - assert_eq!( - cancel.get("cancelled").and_then(Value::as_bool), - Some(false), - "an unknown run id is reported as not-cancelled, not as an error: {cancel}" - ); - assert_eq!( - cancel.get("run_id").and_then(Value::as_str), - Some("not-a-live-run") - ); - - harness.join.abort(); -} - -/// `skills_read_resource` — the happy read plus the traversal and symlink -/// guards, which are the reason this controller has a hand-written path jail -/// rather than a plain `fs::read`. -#[tokio::test] -async fn skills_read_resource_reads_a_bundle_file_and_refuses_escapes() { - let _lock = env_lock(); - let harness = setup(Vec::new()).await; - plant_skill(&harness.workspace, "planted-resource-skill", "unused"); - - let read = rpc( - &harness.rpc_base, - 140, - "openhuman.skills_read_resource", - json!({ "workflow_id": "planted-resource-skill", "relative_path": "references/note.md" }), - ) - .await; - let read = ok(&read, "skills_read_resource"); - assert_eq!( - read.get("content").and_then(Value::as_str), - Some("PLANTED_RESOURCE_BODY\n"), - "the resource body must come back verbatim: {read}" - ); - assert_eq!( - read.get("bytes").and_then(Value::as_u64), - Some("PLANTED_RESOURCE_BODY\n".len() as u64), - "`bytes` must be the on-disk size, not a rounded or char count: {read}" - ); - assert_eq!( - read.get("relative_path").and_then(Value::as_str), - Some("references/note.md"), - "the request path must be echoed back: {read}" - ); - assert_eq!( - read.get("workflow_id").and_then(Value::as_str), - Some("planted-resource-skill") - ); - - // Traversal: `..` is rejected on the component walk, before any filesystem - // call — so this must fail even though the target exists. - let traversal = rpc( - &harness.rpc_base, - 141, - "openhuman.skills_read_resource", - json!({ "workflow_id": "planted-resource-skill", "relative_path": "../../../etc/passwd" }), - ) - .await; - let message = error_message(&traversal, "skills_read_resource traversal"); - assert!( - message.contains(".."), - "the traversal refusal must name the offending component, got: {message}" - ); - - // An absolute path is a separate rejection from `..`. - let absolute = rpc( - &harness.rpc_base, - 142, - "openhuman.skills_read_resource", - json!({ "workflow_id": "planted-resource-skill", "relative_path": "/etc/passwd" }), - ) - .await; - let message = error_message(&absolute, "skills_read_resource absolute"); - assert!( - message.contains("relative"), - "an absolute path must be refused for being absolute, got: {message}" - ); - - // A symlinked leaf pointing outside the bundle is caught by the - // `symlink_metadata` pre-check, not followed. - #[cfg(unix)] - { - let outside = harness.workspace.join("outside-secret.txt"); - std::fs::write(&outside, "SHOULD_NOT_BE_READABLE\n").expect("write outside file"); - let link = harness - .workspace - .join("skills") - .join("planted-resource-skill") - .join("references") - .join("escape.md"); - std::os::unix::fs::symlink(&outside, &link).expect("create symlink"); - - let symlinked = rpc( - &harness.rpc_base, - 143, - "openhuman.skills_read_resource", - json!({ "workflow_id": "planted-resource-skill", "relative_path": "references/escape.md" }), - ) - .await; - let message = error_message(&symlinked, "skills_read_resource symlink"); - assert!( - message.contains("symlink"), - "a symlinked leaf must be refused as a symlink, got: {message}" - ); - assert!( - !message.contains("SHOULD_NOT_BE_READABLE"), - "the refusal must not leak the target's contents: {message}" - ); - } - - // An unknown skill id is refused before any path work. - let unknown = rpc( - &harness.rpc_base, - 144, - "openhuman.skills_read_resource", - json!({ "workflow_id": "no-such-skill", "relative_path": "references/note.md" }), - ) - .await; - assert!( - unknown.get("error").is_some(), - "reading a resource of an unknown skill must error: {unknown}" - ); - - harness.join.abort(); -} - -/// `skills_install_from_url` — the SSRF guards it exists to enforce, then the -/// loopback happy path behind the documented escape hatch. -#[tokio::test] -async fn skills_install_from_url_enforces_its_url_policy_then_installs() { - let _lock = env_lock(); - let (fixture_addr, fixture_join) = serve_fixture_catalog().await; - let harness = setup(vec![EnvVarGuard::set( - "OPENHUMAN_SKILL_INSTALL_ALLOW_LOCAL_HTTP", - "1", - )]) - .await; - - // Guard 1: plain HTTP to a non-loopback host is refused even with the - // local-HTTP hatch open — the hatch is loopback-only. - let plain_http = rpc( - &harness.rpc_base, - 150, - "openhuman.skills_install_from_url", - json!({ "url": "http://example.com/skill.md" }), - ) - .await; - let message = error_message(&plain_http, "install_from_url plain http"); - assert!( - message.contains("https"), - "a non-loopback http URL must be refused for its scheme, got: {message}" - ); - - // Guard 2: an https URL whose host is a private/loopback literal is the - // SSRF vector this controller's host check exists for. - for host in ["127.0.0.1", "10.0.0.1", "169.254.169.254"] { - let private = rpc( - &harness.rpc_base, - 151, - "openhuman.skills_install_from_url", - json!({ "url": format!("https://{host}/skill.md") }), - ) - .await; - let message = error_message(&private, "install_from_url private host"); - assert!( - message.contains(host) && message.contains("not allowed"), - "https://{host} must be refused by name, got: {message}" - ); - } - - // Guard 3: an https URL that is not a single `.md` file. - let not_md = rpc( - &harness.rpc_base, - 152, - "openhuman.skills_install_from_url", - json!({ "url": "https://example.com/some/repo" }), - ) - .await; - let message = error_message(¬_md, "install_from_url non-md"); - assert!( - message.contains("unsupported url form"), - "a non-`.md` target must be refused as an unsupported form, got: {message}" - ); - - // Happy path: loopback HTTP with the hatch open, against the fixture. - let installed = rpc( - &harness.rpc_base, - 153, - "openhuman.skills_install_from_url", - json!({ - "url": format!("http://127.0.0.1:{}/skills/url-installed-skill/SKILL.md", fixture_addr.port()), - "timeout_secs": 30 - }), - ) - .await; - let installed = ok(&installed, "skills_install_from_url happy path"); - assert!( - installed - .get("url") - .and_then(Value::as_str) - .is_some_and(|u| u.contains("url-installed-skill")), - "the installed URL must be echoed: {installed}" - ); - // NOTE the field name. The controller schema declares this output as - // `new_skills`; the handler emits `new_workflows`. See - // `~/tinyhuman/bugs/e2e-wave-skills-schema-output-name-drift.md`. Asserted - // against what the code does, and against what the frontend reads - // (`app/src/services/api/skillsApi.ts:400`). - let new_workflows = installed - .get("new_workflows") - .and_then(Value::as_array) - .unwrap_or_else(|| panic!("install result has no `new_workflows`: {installed}")); - assert!( - new_workflows - .iter() - .any(|s| s.as_str() == Some("url-installed-skill")), - "the freshly installed slug must appear in `new_workflows`: {installed}" - ); - assert!( - installed.get("new_skills").is_none(), - "the schema's declared `new_skills` is NOT what the handler emits; if this \ - starts passing the schema and the handler have been reconciled and this \ - suite plus the bug note need updating: {installed}" - ); - - // Installing the same URL again is an idempotent success reporting no new - // slugs — not a duplicate-directory error. - let again = rpc( - &harness.rpc_base, - 154, - "openhuman.skills_install_from_url", - json!({ - "url": format!("http://127.0.0.1:{}/skills/url-installed-skill/SKILL.md", fixture_addr.port()) - }), - ) - .await; - let again = ok(&again, "skills_install_from_url idempotent"); - assert_eq!( - again - .get("new_workflows") - .and_then(Value::as_array) - .map(Vec::len), - Some(0), - "a repeat install must report zero new slugs: {again}" - ); - - fixture_join.abort(); - harness.join.abort(); -} - -// ── skill_registry ────────────────────────────────────────────────────────── - -/// `skill_registry_categories` — the distinct, sorted, non-empty categories of -/// the catalog. -#[tokio::test] -async fn skill_registry_categories_are_distinct_sorted_and_drop_the_blank() { - let _lock = env_lock(); - let (fixture_addr, fixture_join) = serve_fixture_catalog().await; - let fixture_base = format!("http://{fixture_addr}"); - let harness = setup(vec![ - EnvVarGuard::set( - "OPENHUMAN_SKILL_REGISTRY_CATALOG_URL", - &format!("{fixture_base}/skills.json"), - ), - EnvVarGuard::set( - "OPENHUMAN_SKILL_REGISTRY_DOWNLOAD_BASE_URL", - &format!("{fixture_base}/skills"), - ), - ]) - .await; - - let response = rpc( - &harness.rpc_base, - 160, - "openhuman.skill_registry_categories", - json!({}), - ) - .await; - let response = ok(&response, "skill_registry_categories"); - let categories: Vec<&str> = response - .get("categories") - .and_then(Value::as_array) - .unwrap_or_else(|| panic!("no `categories` array: {response}")) - .iter() - .map(|c| { - c.as_str() - .unwrap_or_else(|| panic!("a category must be a string: {c}")) - }) - .collect(); - - assert!( - categories.contains(&"software-development") && categories.contains(&"productivity"), - "both fixture categories must be present, got {categories:?}" - ); - assert!( - !categories.iter().any(|c| c.is_empty()), - "the blank category must be filtered out, got {categories:?}" - ); - let mut sorted = categories.clone(); - sorted.sort_unstable(); - assert_eq!( - categories, sorted, - "categories must come back sorted, got {categories:?}" - ); - let mut deduped = sorted.clone(); - deduped.dedup(); - assert_eq!( - categories.len(), - deduped.len(), - "categories must be distinct, got {categories:?}" - ); - - fixture_join.abort(); - harness.join.abort(); -} - -// ── javascript ────────────────────────────────────────────────────────────── - -/// `javascript_list_tools` and `javascript_execute_tool` — the runtime bridge -/// the agent reaches its tool registry through. -/// -/// The happy path executes a real tool (`file_read`) against a file this test -/// wrote into the action sandbox, so it proves the whole chain: build the -/// registry, resolve by name, execute, and wrap the result in the MCP-style -/// envelope. -#[tokio::test] -async fn javascript_bridge_lists_and_executes_a_real_tool() { - let _lock = env_lock(); - let harness = setup(Vec::new()).await; - - let listed = rpc( - &harness.rpc_base, - 170, - "openhuman.javascript_list_tools", - json!({}), - ) - .await; - // Assert the envelope explicitly before unwrapping: this handler always - // logs, so it is always wrapped, and that is the shape a caller must parse. - let listed_raw = ok(&listed, "javascript_list_tools"); - assert!( - listed_raw.get("logs").is_some_and(Value::is_array), - "a handler that logs must return the `{{result, logs}}` envelope: {listed_raw}" - ); - let listed = payload(&listed, "javascript_list_tools"); - let tools = listed - .get("tools") - .and_then(Value::as_array) - .unwrap_or_else(|| panic!("no `tools` array: {listed}")); - assert!( - !tools.is_empty(), - "the bridge must expose a non-empty tool registry: {listed}" - ); - - let file_read = tools - .iter() - .find(|t| t.get("name").and_then(Value::as_str) == Some("file_read")) - .unwrap_or_else(|| { - panic!( - "`file_read` must be in the registry; got {:?}", - tools - .iter() - .filter_map(|t| t.get("name").and_then(Value::as_str)) - .collect::>() - ) - }); - // The schema documents each summary's fields; a caller renders from them. - for field in ["description", "permission_level", "parameters"] { - assert!( - file_read.get(field).is_some(), - "a tool summary must carry `{field}`: {file_read}" - ); - } - // Sorted by name, per `ops::list_tools`. - let names: Vec<&str> = tools - .iter() - .filter_map(|t| t.get("name").and_then(Value::as_str)) - .collect(); - let mut sorted = names.clone(); - sorted.sort_unstable(); - assert_eq!(names, sorted, "the tool list must be sorted by name"); - - // Happy path: read a file the action sandbox actually holds. - let action_dir = std::env::var("OPENHUMAN_ACTION_DIR").expect("action dir set by setup()"); - std::fs::write( - Path::new(&action_dir).join("bridge-fixture.txt"), - "BRIDGE_FIXTURE_BODY\n", - ) - .expect("write action-dir fixture"); - - let executed = rpc( - &harness.rpc_base, - 171, - "openhuman.javascript_execute_tool", - json!({ "tool_name": "file_read", "args": { "path": "bridge-fixture.txt" } }), - ) - .await; - let executed = payload(&executed, "javascript_execute_tool file_read"); - assert_eq!( - executed.get("tool_name").and_then(Value::as_str), - Some("file_read"), - "the executed tool name must be echoed: {executed}" - ); - assert!( - executed.get("elapsed_ms").is_some_and(Value::is_number), - "`elapsed_ms` must be a number: {executed}" - ); - let result = executed - .get("result") - .unwrap_or_else(|| panic!("no `result` envelope: {executed}")); - assert_eq!( - result.get("is_error").and_then(Value::as_bool), - Some(false), - "reading a file that exists must not be an error result: {result}" - ); - assert!( - result.to_string().contains("BRIDGE_FIXTURE_BODY"), - "the tool's output must carry the file's contents: {result}" - ); - - // Failure path 1: a registered tool given bad args fails *inside* the - // envelope — `is_error: true`, not a JSON-RPC error. - let bad_args = rpc( - &harness.rpc_base, - 172, - "openhuman.javascript_execute_tool", - json!({ "tool_name": "file_read", "args": { "path": "definitely-not-here.txt" } }), - ) - .await; - let bad_args = payload(&bad_args, "javascript_execute_tool bad args"); - assert_eq!( - bad_args.get("tool_name").and_then(Value::as_str), - Some("file_read"), - "a failing execution still echoes the tool name: {bad_args}" - ); - assert_eq!( - bad_args - .get("result") - .and_then(|r| r.get("is_error")) - .and_then(Value::as_bool), - Some(true), - "a tool-level failure must surface as `is_error` in the envelope, not as \ - a transport error: {bad_args}" - ); - - // Failure path 2: a name the registry does not hold is a dispatch error, - // which is a different outcome from the above and must stay different. - let unknown = rpc( - &harness.rpc_base, - 173, - "openhuman.javascript_execute_tool", - json!({ "tool_name": "no_such_tool_anywhere", "args": {} }), - ) - .await; - let message = error_message(&unknown, "javascript_execute_tool unknown tool"); - assert!( - message.contains("unknown tool") && message.contains("no_such_tool_anywhere"), - "an unregistered name must be refused by name, got: {message}" - ); - - // Failure path 3: the required param is missing entirely. - let no_name = rpc( - &harness.rpc_base, - 174, - "openhuman.javascript_execute_tool", - json!({ "args": {} }), - ) - .await; - assert!( - error_message(&no_name, "javascript_execute_tool no name").contains("tool_name"), - "an absent `tool_name` must be named in the error: {no_name}" - ); - - harness.join.abort(); -} diff --git a/tests/raw_coverage/tool_registry_approval_raw_coverage_e2e.rs b/tests/raw_coverage/tool_registry_approval_raw_coverage_e2e.rs index e47fdeff203..3ea3f1dfe31 100644 --- a/tests/raw_coverage/tool_registry_approval_raw_coverage_e2e.rs +++ b/tests/raw_coverage/tool_registry_approval_raw_coverage_e2e.rs @@ -5,37 +5,29 @@ //! direct public API calls cover persistence/redaction/provider branches that //! are otherwise only indirectly reachable from the controllers. -use std::path::{Path, PathBuf}; +use std::path::Path; use std::sync::{Arc, Mutex, OnceLock}; use std::time::{Duration, Instant}; use axum::http::header::AUTHORIZATION; use reqwest::StatusCode; -use rusqlite::{params, Connection}; use serde_json::{json, Map, Value}; use tempfile::{tempdir, TempDir}; use openhuman_core::agent::turn_origin::{self, AgentTurnOrigin}; -use openhuman_core::config::schema::{CapabilityProviderConfig, CapabilityProviderTrustState}; use openhuman_core::config::Config; use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR}; use openhuman_core::mcp::registry::connections; use openhuman_core::mcp::registry::types::{CommandKind, InstalledServer, Transport}; use openhuman_core::security::approval::gate::{ - parse_approval_reply, ApprovalChatContext, ApprovalGate, APPROVAL_CHAT_CONTEXT, + ApprovalChatContext, ApprovalGate, APPROVAL_CHAT_CONTEXT, }; -use openhuman_core::security::approval::store as approval_store; use openhuman_core::security::approval::{ - all_approval_controller_schemas, all_approval_registered_controllers, redact_args, - summarize_action, ApprovalDecision, ExecutionOutcome, GateOutcome, PendingApproval, + all_approval_controller_schemas, all_approval_registered_controllers, ExecutionOutcome, GateOutcome, }; use openhuman_core::security::{live_policy, SecurityPolicy}; use openhuman_core::tools::registry::{ - all_tool_registry_controller_schemas, all_tool_registry_registered_controllers, - capability_provider_by_id, capability_provider_diagnostics, capability_provider_registry, - denials, get_tool, is_capability_provider_trusted_enabled, list_capability_providers, - list_tools, normalize_capability_provider_id, registry_entries, registry_entries_for_config, - CapabilityProviderRegistryError, + denials, registry_entries, registry_entries_for_config, }; use openhuman_rpc::server::build_core_http_router; @@ -252,40 +244,6 @@ fn error_message<'a>(value: &'a Value, context: &str) -> &'a str { .unwrap_or_else(|| panic!("{context}: error missing message: {value}")) } -fn provider( - id: &str, - display_name: &str, - trust_state: CapabilityProviderTrustState, - enabled: bool, -) -> CapabilityProviderConfig { - CapabilityProviderConfig { - id: id.to_string(), - display_name: display_name.to_string(), - source_uri: Some(format!(" https://example.com/providers/{id} ")), - source_digest: Some(" sha256:feedface ".to_string()), - trust_state, - enabled, - } -} - -fn approval_db_path(config: &Config) -> PathBuf { - config.workspace_dir.join("approval").join("approval.db") -} - -fn pending( - request_id: &str, - _session_id: &str, - expires_at: Option>, -) -> PendingApproval { - PendingApproval::new( - request_id, - "tools.composio_execute", - "tools.composio_execute(action=execute, 42 bytes)", - json!({ "action": "execute", "tool_slug": "GMAIL_SEND_EMAIL" }), - expires_at, - ) -} - fn test_mcp_server() -> InstalledServer { InstalledServer { server_id: format!("tool-registry-test-{}", uuid::Uuid::new_v4()), @@ -459,199 +417,6 @@ enabled = true harness.rpc_join.abort(); } -#[test] -fn tool_registry_public_api_lists_gets_and_validates_ids() { - let listed = list_tools() - .into_cli_compatible_json() - .expect("list_tools json"); - let tools = listed - .get("tools") - .and_then(Value::as_array) - .expect("listed tools"); - let first_tool_id = tools - .first() - .and_then(|tool| tool.get("tool_id")) - .and_then(Value::as_str) - .expect("first tool id"); - - let found = get_tool(first_tool_id) - .expect("get first tool") - .into_cli_compatible_json() - .expect("get_tool json"); - assert_eq!( - found.get("tool_id").and_then(Value::as_str), - Some(first_tool_id) - ); - assert!(get_tool(" ") - .expect_err("blank id should fail") - .contains("non-empty")); - assert!(get_tool("missing.tool") - .expect_err("missing id should fail") - .contains("missing.tool")); -} - -#[test] -fn capability_provider_public_api_normalizes_lookup_and_error_branches() { - let config = Config { - capability_providers: vec![ - provider( - " Team Tools ", - " ", - CapabilityProviderTrustState::Trusted, - true, - ), - provider( - "draft_tools", - "Draft Tools", - CapabilityProviderTrustState::Untrusted, - true, - ), - provider( - "disabled.tools", - "Disabled Tools", - CapabilityProviderTrustState::Trusted, - false, - ), - ], - ..Config::default() - }; - - assert_eq!( - normalize_capability_provider_id(" Team Tools "), - Ok("team-tools".to_string()) - ); - assert!(normalize_capability_provider_id("!!!").is_err()); - assert!(normalize_capability_provider_id(&"x".repeat(120)).is_err()); - - let registry = capability_provider_registry(&config).expect("provider registry"); - let listed = registry.list(); - assert_eq!(listed.len(), 3); - assert_eq!(listed[2].id, "team-tools"); - assert_eq!( - listed[2].display_name, "team-tools", - "empty display_name should fall back to normalized id" - ); - assert_eq!( - listed[2].source_uri.as_deref(), - Some("https://example.com/providers/ Team Tools") - ); - assert!(registry.get("TEAM TOOLS").is_some()); - assert!(registry.get("!!!").is_none()); - assert!(registry.is_trusted_enabled("team tools")); - assert!(!registry.is_trusted_enabled("draft_tools")); - assert!(!registry.is_trusted_enabled("disabled.tools")); - - assert_eq!(list_capability_providers(&config).unwrap().len(), 3); - let diagnostics = capability_provider_diagnostics(&config); - assert_eq!(diagnostics.total_providers, 3); - assert_eq!(diagnostics.enabled_providers, 2); - assert_eq!(diagnostics.trusted_providers, 2); - assert_eq!(diagnostics.trusted_enabled_providers, 1); - assert!(diagnostics.registry_errors.is_empty()); - assert_eq!( - capability_provider_by_id(&config, "team tools") - .unwrap() - .expect("team provider") - .id, - "team-tools" - ); - assert!(is_capability_provider_trusted_enabled( - &config, - "team tools" - )); - - let duplicate_config = Config { - capability_providers: vec![ - provider( - "Team Tools", - "Team Tools", - CapabilityProviderTrustState::Trusted, - true, - ), - provider( - "team-tools", - "Team Tools", - CapabilityProviderTrustState::Trusted, - true, - ), - ], - ..Config::default() - }; - assert!(list_capability_providers(&duplicate_config).is_err()); - let diagnostics = capability_provider_diagnostics(&duplicate_config); - assert_eq!(diagnostics.total_providers, 2); - assert!(diagnostics.registry_errors[0].contains("duplicate")); - - let invalid_config = Config { - capability_providers: vec![provider( - "!!!", - "Invalid Tools", - CapabilityProviderTrustState::Trusted, - true, - )], - ..Config::default() - }; - let invalid_err = list_capability_providers(&invalid_config).expect_err("invalid provider id"); - assert_eq!( - invalid_err.to_string(), - CapabilityProviderRegistryError::InvalidId { - raw: "!!!".to_string() - } - .to_string() - ); - assert!(!is_capability_provider_trusted_enabled( - &invalid_config, - "invalid" - )); - let invalid_diagnostics = capability_provider_diagnostics(&invalid_config); - assert_eq!(invalid_diagnostics.total_providers, 1); - assert_eq!(invalid_diagnostics.enabled_providers, 0); - assert!(invalid_diagnostics.registry_errors[0].contains("invalid provider id")); -} - -#[test] -fn tool_registry_diagnostics_for_config_reports_audit_success_and_policy_shape() { - let dir = tempdir().expect("tempdir"); - let config = Config { - workspace_dir: dir.path().to_path_buf(), - ..Config::default() - }; - - let diagnostics = openhuman_core::tools::registry::ops::diagnostics_for_config(&config) - .into_cli_compatible_json() - .expect("diagnostics json"); - assert!(diagnostics - .get("total_tools") - .and_then(Value::as_u64) - .is_some_and(|count| count > 0)); - assert_eq!( - diagnostics.pointer("/mcp_write_audit/enabled"), - Some(&json!(true)) - ); - assert_eq!( - diagnostics.pointer("/mcp_write_audit/last_error"), - Some(&Value::Null) - ); - assert!(diagnostics - .pointer("/mcp_write_audit/recent_rows") - .and_then(Value::as_u64) - .is_some()); - assert_eq!( - diagnostics.pointer("/posture/autonomy_level"), - Some(&json!("supervised")) - ); - assert!(diagnostics - .pointer("/policy_surfaces") - .and_then(Value::as_array) - .expect("policy surfaces") - .iter() - .any(|surface| surface.as_str() == Some("tool_registry.diagnostics"))); - assert_eq!( - diagnostics.pointer("/mcp_allowlists/server_count"), - Some(&json!(0)) - ); -} - #[tokio::test(flavor = "current_thread")] async fn tool_registry_entries_fall_back_on_current_thread_runtime() { let entries = registry_entries(); @@ -732,81 +497,6 @@ async fn tool_registry_entries_include_connected_mcp_client_tools() { assert!(connections::disconnect_for_config(&other_config, &other_server.server_id).await); } -#[tokio::test] -async fn tool_registry_schema_handlers_validate_and_return_payloads() { - // Acquire the env lock — this test loads Config via the diagnostics - // handler, and a sibling test temporarily points OPENHUMAN_WORKSPACE at - // a file to exercise the load-failure branch. Without the lock those - // two can race and this test sees the corrupted env. - let _lock = env_lock(); - let schemas = all_tool_registry_controller_schemas(); - assert_eq!( - schemas - .iter() - .map(|schema| schema.function) - .collect::>(), - vec!["list", "get", "diagnostics"] - ); - let controllers = all_tool_registry_registered_controllers(); - assert_eq!(controllers.len(), schemas.len()); - - let list_handler = controllers - .iter() - .find(|controller| controller.schema.function == "list") - .expect("list controller") - .handler; - let list_value = list_handler(Map::new()).await.expect("list handler"); - let tools = list_value - .get("tools") - .and_then(Value::as_array) - .expect("tools array"); - assert!(tools - .iter() - .any(|tool| tool.get("tool_id").and_then(Value::as_str) == Some("memory.search"))); - - let get_handler = controllers - .iter() - .find(|controller| controller.schema.function == "get") - .expect("get controller") - .handler; - assert!(get_handler(Map::new()) - .await - .expect_err("missing tool_id") - .contains("non-empty string")); - let mut numeric_tool_id = Map::new(); - numeric_tool_id.insert("tool_id".to_string(), json!(42)); - assert!(get_handler(numeric_tool_id) - .await - .expect_err("numeric tool_id") - .contains("non-empty string")); - let mut blank_tool_id = Map::new(); - blank_tool_id.insert("tool_id".to_string(), json!(" ")); - assert!(get_handler(blank_tool_id) - .await - .expect_err("blank tool_id") - .contains("non-empty string")); - let mut valid_tool_id = Map::new(); - valid_tool_id.insert("tool_id".to_string(), json!("tools.web_search")); - let tool_value = get_handler(valid_tool_id).await.expect("get handler"); - assert_eq!( - tool_value.get("tool_id").and_then(Value::as_str), - Some("tools.web_search") - ); - - let diagnostics_handler = controllers - .iter() - .find(|controller| controller.schema.function == "diagnostics") - .expect("diagnostics controller") - .handler; - let diagnostics_value = diagnostics_handler(Map::new()) - .await - .expect("diagnostics handler"); - assert!(diagnostics_value - .get("total_tools") - .and_then(Value::as_u64) - .is_some_and(|count| count > 0)); -} - #[tokio::test] async fn tool_registry_diagnostics_reports_config_and_audit_store_failures() { let _lock = env_lock(); @@ -836,285 +526,6 @@ async fn tool_registry_diagnostics_reports_config_and_audit_store_failures() { .is_some_and(|error| !error.is_empty())); } -#[test] -fn approval_redaction_and_store_cover_shape_expiry_migration_and_audit_branches() { - let dir = tempdir().expect("tempdir"); - let config = Config { - workspace_dir: dir.path().to_path_buf(), - ..Config::default() - }; - - let raw_args = json!({ - "action": "execute", - "tool_slug": "GMAIL_SEND_EMAIL", - "integration": "gmail", - "body": "Hello from /Users/alice/private.txt", - "recipients": ["a@example.com", "b@example.com"], - "metadata": { - "Subject": "Confidential subject", - "token": "sk-secret", - "auth": true, - "message": 42, - "password": null, - "user": { "id": "user-123", "name": "Alice" }, - "attempts": 3, - "confirmed": true, - "nullable": null, - "safe_path": "C:\\Users\\bob\\Desktop\\report.txt", - "safe_list": [ - "open /Users/frank/Desktop/report.txt", - { "content": "nested secret" } - ] - } - }); - let redacted = redact_args(&raw_args); - assert_eq!(redacted["action"], json!("execute")); - assert_eq!(redacted["body"], json!("")); - assert_eq!(redacted["recipients"], json!("")); - assert_eq!( - redacted.pointer("/metadata/Subject"), - Some(&json!("")) - ); - assert_eq!( - redacted.pointer("/metadata/attempts"), - Some(&json!(3)), - "non-sensitive numeric fields should pass through" - ); - assert_eq!( - redacted.pointer("/metadata/auth"), - Some(&json!("")) - ); - assert_eq!( - redacted.pointer("/metadata/message"), - Some(&json!("")) - ); - assert_eq!(redacted.pointer("/metadata/password"), Some(&Value::Null)); - assert_eq!( - redacted.pointer("/metadata/user"), - Some(&json!("")) - ); - assert_eq!( - redacted.pointer("/metadata/safe_list/0"), - Some(&json!("open /Desktop/report.txt")) - ); - assert_eq!( - redacted.pointer("/metadata/safe_list/1/content"), - Some(&json!("")) - ); - assert_eq!( - redact_args(&json!( - "open /home/carol/report.md and C:\\Users\\dave\\x.txt" - )), - json!("open /report.md and \\x.txt") - ); - assert_eq!(redact_args(&json!("/Users/erin")), json!("")); - let summary = summarize_action("tools.composio_execute", &raw_args); - assert!(summary.contains("action=execute")); - assert!(summary.contains("tool_slug=GMAIL_SEND_EMAIL")); - assert!(summary.contains("integration=gmail")); - let summary_without_safe_fields = summarize_action("tools.empty", &json!(["opaque"])); - assert!(summary_without_safe_fields.starts_with("tools.empty (")); - - approval_store::insert_pending( - &config, - &pending( - "expired", - "session-a", - Some(chrono::Utc::now() - chrono::Duration::minutes(5)), - ), - "session-a", - ) - .expect("insert expired"); - approval_store::insert_pending( - &config, - &pending( - "active", - "session-a", - Some(chrono::Utc::now() + chrono::Duration::minutes(5)), - ), - "session-a", - ) - .expect("insert active"); - approval_store::insert_pending( - &config, - &pending("other-session", "session-b", None), - "session-b", - ) - .expect("insert no-ttl"); - - let rows = approval_store::list_pending(&config).expect("list pending"); - let ids = rows - .iter() - .map(|row| row.request_id.as_str()) - .collect::>(); - assert_eq!(ids, vec!["active", "other-session"]); - assert_eq!( - approval_store::get_decision(&config, "expired").expect("expired decision"), - Some(ApprovalDecision::Deny) - ); - - let removed = approval_store::purge_session(&config, "session-b").expect("purge session"); - assert_eq!(removed, 1); - assert_eq!( - approval_store::purge_session(&config, "missing-session").unwrap(), - 0 - ); - - let decided = approval_store::decide(&config, "active", ApprovalDecision::ApproveOnce) - .expect("decide active") - .expect("active row"); - assert_eq!(decided.request_id, "active"); - assert!(!approval_store::record_execution( - &config, - "missing", - ExecutionOutcome::Aborted, - Some("not found"), - ) - .expect("unknown record execution")); - assert!(approval_store::record_execution( - &config, - "active", - ExecutionOutcome::Failure, - Some("upstream Authorization: Bearer sk-live-abcdefghijklmnopqrstuvwxyz failed"), - ) - .expect("record failed execution")); - assert!(!approval_store::record_execution( - &config, - "active", - ExecutionOutcome::Success, - Some("late rewrite"), - ) - .expect("idempotent execution")); - - let audit = approval_store::list_recent_decisions(&config, 0).expect("recent decisions"); - assert_eq!(audit.len(), 1, "zero limit should clamp to one"); - assert_eq!(audit[0].request_id, "active"); - assert_eq!(audit[0].decision, ApprovalDecision::ApproveOnce); - - let db_path = approval_db_path(&config); - let conn = Connection::open(&db_path).expect("open approval db"); - conn.execute( - "INSERT INTO pending_approvals - (request_id, tool_name, action_summary, args_redacted, session_id, created_at, - decided_at, decision) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", - params![ - "corrupt-json", - "tools.web_search", - "corrupt args", - "{not valid json", - "session-a", - chrono::Utc::now().to_rfc3339(), - chrono::Utc::now().to_rfc3339(), - "deny", - ], - ) - .expect("insert corrupt audit row"); - drop(conn); - let audit = approval_store::list_recent_decisions(&config, 10).expect("audit with corrupt row"); - let corrupt = audit - .iter() - .find(|row| row.request_id == "corrupt-json") - .expect("corrupt audit row"); - assert_eq!( - corrupt.args_redacted, - json!({ "_error": "args_redacted not valid JSON" }) - ); - - let legacy_dir = tempdir().expect("legacy tempdir"); - let legacy_config = Config { - workspace_dir: legacy_dir.path().to_path_buf(), - ..Config::default() - }; - let legacy_db = approval_db_path(&legacy_config); - std::fs::create_dir_all(legacy_db.parent().expect("legacy db parent")) - .expect("create legacy db dir"); - let legacy_conn = Connection::open(&legacy_db).expect("open legacy db"); - legacy_conn - .execute_batch( - "CREATE TABLE pending_approvals ( - request_id TEXT PRIMARY KEY, - tool_name TEXT NOT NULL, - action_summary TEXT NOT NULL, - args_redacted TEXT NOT NULL, - session_id TEXT NOT NULL, - created_at TEXT NOT NULL, - expires_at TEXT, - decided_at TEXT, - decision TEXT - );", - ) - .expect("create legacy schema"); - legacy_conn - .execute( - "INSERT INTO pending_approvals - (request_id, tool_name, action_summary, args_redacted, session_id, created_at) - VALUES ('legacy', 'tools.web_search', 'legacy', '{}', 'legacy-session', ?1)", - params![chrono::Utc::now().to_rfc3339()], - ) - .expect("insert legacy row"); - drop(legacy_conn); - - assert_eq!( - approval_store::list_pending(&legacy_config) - .expect("migrated pending") - .len(), - 1 - ); - approval_store::decide(&legacy_config, "legacy", ApprovalDecision::ApproveOnce) - .expect("decide legacy"); - assert!(approval_store::record_execution( - &legacy_config, - "legacy", - ExecutionOutcome::Success, - None, - ) - .expect("record execution after migration")); -} - -#[test] -fn approval_reply_parser_accepts_explicit_yes_no_only() { - for decision in [ - ApprovalDecision::ApproveOnce, - ApprovalDecision::ApproveAlwaysForTool, - ApprovalDecision::Deny, - ] { - assert_eq!( - ApprovalDecision::from_str(decision.as_str()), - Some(decision) - ); - } - assert_eq!(ApprovalDecision::from_str("maybe"), None); - assert!(ApprovalDecision::ApproveOnce.is_approve()); - assert!(ApprovalDecision::ApproveAlwaysForTool.is_approve()); - assert!(!ApprovalDecision::Deny.is_approve()); - - for outcome in [ - ExecutionOutcome::Success, - ExecutionOutcome::Failure, - ExecutionOutcome::Aborted, - ] { - assert_eq!(ExecutionOutcome::from_str(outcome.as_str()), Some(outcome)); - } - assert_eq!(ExecutionOutcome::from_str("partial"), None); - assert_eq!( - serde_json::to_string(&ExecutionOutcome::Aborted).expect("serialize outcome"), - "\"aborted\"" - ); - - assert_eq!( - parse_approval_reply(" yes "), - Some(ApprovalDecision::ApproveOnce) - ); - assert_eq!( - parse_approval_reply("APPROVED"), - Some(ApprovalDecision::ApproveOnce) - ); - assert_eq!(parse_approval_reply("n"), Some(ApprovalDecision::Deny)); - assert_eq!(parse_approval_reply("denied"), Some(ApprovalDecision::Deny)); - assert_eq!(parse_approval_reply("maybe later"), None); -} - #[tokio::test] async fn approval_schema_handlers_validate_params_and_surface_empty_gate_state() { let schemas = all_approval_controller_schemas(); diff --git a/tests/raw_coverage/tools_composio_network_leftovers_raw_coverage_e2e.rs b/tests/raw_coverage/tools_composio_network_leftovers_raw_coverage_e2e.rs index 4893ec4a3af..629c335e155 100644 --- a/tests/raw_coverage/tools_composio_network_leftovers_raw_coverage_e2e.rs +++ b/tests/raw_coverage/tools_composio_network_leftovers_raw_coverage_e2e.rs @@ -5,9 +5,9 @@ use std::collections::HashMap; use std::path::Path; use std::sync::{Arc, Mutex, OnceLock}; -use axum::body::{to_bytes, Bytes}; +use axum::body::to_bytes; use axum::extract::{Request, State}; -use axum::http::{HeaderMap, Method, StatusCode, Uri}; +use axum::http::{Method, StatusCode}; use axum::response::{IntoResponse, Response}; use axum::routing::any; use axum::{Json, Router}; @@ -19,11 +19,10 @@ use openhuman_core::config::Config; use openhuman_core::security::credentials::{ AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME, }; -use openhuman_core::security::SecurityPolicy; use tinytools::{Tool, ToolCallOptions}; use openhuman_core::tools::{ - ComposioAuthorizeTool, ComposioListConnectionsTool, ComposioListToolkitsTool, - ComposioListToolsTool, SpawnSubagentTool}; + ComposioListConnectionsTool, ComposioListToolkitsTool, + ComposioListToolsTool}; static ENV_LOCK: &OnceLock> = &crate::SHARED_ENV_LOCK; @@ -241,7 +240,7 @@ async fn round20_backend_agent_tools_cover_markdown_filtering_and_errors() { } #[tokio::test] -async fn round20_composio_ops_cover_authorize_scopes_and_direct_factory_edges() { +async fn round20_composio_ops_cover_authorize_scopes() { let _lock = env_lock(); let state = MockState::default(); let base = start_loopback( @@ -285,41 +284,6 @@ async fn round20_composio_ops_cover_authorize_scopes_and_direct_factory_edges() .value; assert_eq!(listed.tools.len(), 2); - let mut direct = harness.config.clone(); - direct.composio.mode = "direct".to_string(); - direct.composio.api_key = Some(" ck_round20_direct ".to_string()); - direct.save().await.expect("save direct config"); - - let direct_toolkits = ComposioListToolkitsTool::new(Arc::new(direct.clone())) - .execute(json!({})) - .await - .expect("direct list toolkits"); - assert!(!direct_toolkits.is_error); - assert!(direct_toolkits.output().contains("\"toolkits\":[]")); - - let direct_authorize = ComposioAuthorizeTool::new(Arc::new(direct.clone())) - .execute(json!({ "toolkit": "gmail" })) - .await - .expect("direct authorize tool"); - assert!(direct_authorize.is_error); - assert!(direct_authorize.output().contains("direct mode is active")); - - let direct_list_tools = ComposioListToolsTool::new(Arc::new(direct)) - .execute_with_options( - json!({ "include_unconnected": true }), - ToolCallOptions { - prefer_markdown: true, - }, - ) - .await - .expect("direct list tools tool"); - assert!(!direct_list_tools.is_error); - assert_eq!(direct_list_tools.output(), "{\"tools\":[]}"); - assert_eq!( - direct_list_tools.markdown_formatted.as_deref(), - Some("_No composio tools available._") - ); - let requests = state.requests.lock().expect("requests").clone(); let authorize_body = requests .iter() @@ -339,53 +303,6 @@ async fn round20_composio_ops_cover_authorize_scopes_and_direct_factory_edges() .contains("gmail.readonly"))); } -#[tokio::test] -async fn round20_spawn_subagent_covers_validation_schema_and_disabled_worker_branch() { - let _lock = env_lock(); - let tool = SpawnSubagentTool::new(); - - assert_eq!(tool.name(), "spawn_subagent"); - assert_eq!(tool.permission_level().to_string(), "Execute"); - let schema = tool.parameters_schema(); - // The per-toolkit spawn argument went with the integrations specialist. - assert!( - schema["properties"].get("toolkit").is_none(), - "spawn_subagent must not advertise the removed `toolkit` argument" - ); - assert!(schema["properties"]["dedicated_thread"] - .as_object() - .expect("dedicated_thread schema") - .contains_key("description")); - - let missing_agent = tool - .execute(json!({ "prompt": "summarize the thread" })) - .await - .expect("missing agent id returns tool result"); - assert!(missing_agent.is_error); - assert!(missing_agent.output().contains("agent_id")); - - let missing_prompt = tool - .execute(json!({ "agent_id": "researcher" })) - .await - .expect("missing prompt returns tool result"); - assert!(missing_prompt.is_error); - assert!(missing_prompt.output().contains("prompt")); - - let dedicated_thread = tool - .execute(json!({ - "agent_id": "researcher", - "prompt": "summarize", - "dedicated_thread": true - })) - .await - .expect("dedicated thread disabled returns tool result"); - assert!(dedicated_thread.is_error); - // #3049 superseded #1624: dedicated_thread is no longer "temporarily - // disabled". Verify the tool errors (no provider) without requiring - // the exact legacy message. - assert!(!dedicated_thread.output().is_empty()); -} - async fn start_loopback(app: Router) -> String { let listener = tokio::net::TcpListener::bind("127.0.0.1:0") .await @@ -495,130 +412,6 @@ async fn composio_backend_handler(State(state): State, request: Reque } } -async fn composio_direct_handler(State(state): State, request: Request) -> Response { - let method = request.method().clone(); - let uri = request.uri().clone(); - let path = uri.path().to_string(); - let query = uri.query().unwrap_or_default().to_string(); - let api_key = request - .headers() - .get("x-api-key") - .and_then(|value| value.to_str().ok()) - .map(str::to_string); - let bytes = to_bytes(request.into_body(), usize::MAX) - .await - .expect("request body"); - let body: Value = if bytes.is_empty() { - json!({}) - } else { - serde_json::from_slice(&bytes).unwrap_or_else(|_| json!(String::from_utf8_lossy(&bytes))) - }; - state - .requests - .lock() - .expect("requests") - .push(RecordedRequest { - method: method.clone(), - path: path.clone(), - query: query.clone(), - body: body.clone(), - api_key, - }); - - match (method, path.as_str()) { - (Method::GET, "/api/v3/tools") if query.contains("toolkits=broken") => message_fail( - StatusCode::BAD_REQUEST, - "v3 broken list mentions connected_account_id and user_id", - ), - (Method::GET, "/api/v3/tools") if query.contains("toolkits=fallback") => { - fail(StatusCode::BAD_GATEWAY, "fallback to v2 please") - } - (Method::GET, "/api/v3/tools") if query.contains("toolkits=gmail") => Json(json!({ - "items": [ - { - "slug": "gmail-fetch-emails", - "name": "Gmail fetch", - "description": "Fetch Gmail", - "toolkit": { "slug": "gmail" }, - "input_parameters": { - "type": "object", - "properties": { "query": { "type": "string" } } - } - }, - { - "name": "gmail-send-email", - "description": "Send Gmail", - "appName": "gmail" - } - ] - })) - .into_response(), - (Method::GET, "/api/v2/actions") if query.contains("appNames=fallback") => Json(json!({ - "items": [ - { - "name": "FALLBACK_V2", - "appName": "fallback", - "description": "Fallback action", - "enabled": true - } - ] - })) - .into_response(), - (Method::GET, "/api/v2/actions") if query.contains("appNames=broken") => message_fail( - StatusCode::BAD_REQUEST, - "v2 broken list mentions connected_account_id and user_id", - ), - (Method::POST, "/api/v3/tools/execute/GMAIL_FETCH_EMAILS") => Json(json!({ - "successful": true, - "data": { "messages": [{ "id": "msg-round20" }] }, - "error": null - })) - .into_response(), - (Method::POST, "/api/v3/tools/execute/BROKEN_ACTION") => message_fail( - StatusCode::BAD_REQUEST, - "bad execute connected_account_id user_id entity_id", - ), - (Method::POST, "/api/v2/actions/BROKEN_ACTION/execute") => message_fail( - StatusCode::BAD_REQUEST, - "bad legacy connected_account_id user_id entity_id", - ), - (Method::GET, "/api/v3/auth_configs") if query.contains("toolkit_slug=missing") => { - Json(json!({ "items": [] })).into_response() - } - (Method::GET, "/api/v3/connected_accounts") => Json(json!({ - "items": [ - { - "id": "acct-gmail", - "status": "ACTIVE", - "created_at": "2026-05-30T00:00:00Z", - "toolkit": "gmail" - }, - { - "id": "acct-github", - "status": "CONNECTED", - "createdAt": "2026-05-30T00:00:01Z", - "toolkit": { "slug": "github" } - }, - { - "id": "acct-slack", - "status": "PENDING", - "appName": "slack" - }, - { - "id": " ", - "status": "ACTIVE", - "toolkit": "dropme" - } - ] - })) - .into_response(), - _ => fail( - StatusCode::NOT_FOUND, - &format!("unhandled direct {path} {query}"), - ), - } -} - fn ok(data: Value) -> Response { Json(json!({ "success": true, "data": data })).into_response() } @@ -631,6 +424,3 @@ fn fail(status: StatusCode, error: &str) -> Response { .into_response() } -fn message_fail(status: StatusCode, message: &str) -> Response { - (status, Json(json!({ "message": message.to_string() }))).into_response() -} diff --git a/tests/support/memory_engine_fixture.rs b/tests/support/memory_engine_fixture.rs index 8360927b455..44729d83ff1 100644 --- a/tests/support/memory_engine_fixture.rs +++ b/tests/support/memory_engine_fixture.rs @@ -18,7 +18,7 @@ use std::sync::atomic::{AtomicU16, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; use std::time::Duration; -use axum::extract::{Query, State}; +use axum::extract::{Path as UrlPath, Query, State}; use axum::http::{header::AUTHORIZATION, HeaderMap, StatusCode}; use axum::routing::{get, post}; use axum::{Json, Router}; @@ -45,6 +45,9 @@ pub struct HostedState { pub force_status: AtomicU16, /// Milliseconds every `experience` write is delayed by (0 = none). pub delay_ms: AtomicU64, + /// What `GET /memory/{facts,beliefs,understanding}` answers, by + /// `(layer, scope)`. + pub layers: Mutex>>, } pub type Hosted = Arc; @@ -125,14 +128,25 @@ pub async fn experience( .lock() .unwrap() .insert(key, (text, id.clone())); - state.events.lock().unwrap().push(json!({ + // The engine keeps the caller's context (labels, `observed_at`) and stamps + // its own `recorded_at`; the hosted families look records up by label. + let mut context = body["context"].clone(); + if !context.is_object() { + context = json!({}); + } + context["recorded_at"] = json!("2026-09-02T00:00:00Z"); + let mut event = json!({ "id": id, "scope": body["scope"], "modality": body["modality"], "wal_offset": offset, "content": body["content"], - "context": { "recorded_at": "2026-09-02T00:00:00Z" }, - })); + "context": context, + }); + if !body["directives"].is_null() { + event["directives"] = body["directives"].clone(); + } + state.events.lock().unwrap().push(event); ok(json!({ "event_id": id, "status": "captured", "replayed_from_idempotency": false })) } @@ -153,9 +167,24 @@ pub async fn events( .get("limit") .and_then(|v| v.parse().ok()) .unwrap_or(50); + // The engine splits its label filter on commas and keeps an event carrying + // any one of the pieces. + let wanted: Vec = params + .get("labels") + .map(|labels| labels.split(',').map(|l| l.trim().to_string()).collect()) + .unwrap_or_default(); + let labelled = |event: &Value| { + wanted.is_empty() + || event["context"]["labels"].as_array().is_some_and(|labels| { + labels + .iter() + .filter_map(Value::as_str) + .any(|label| wanted.iter().any(|w| w == label)) + }) + }; let mut stream = Vec::new(); for event in state.events.lock().unwrap().iter().rev() { - if event["scope"].as_str() == Some(scope.as_str()) { + if event["scope"].as_str() == Some(scope.as_str()) && labelled(event) { stream.push(event.clone()); stream.push(event.clone()); } @@ -175,12 +204,37 @@ pub async fn recall( } let scope = body["scope"].as_str().unwrap_or_default(); let query = body["query"].as_str().unwrap_or_default().to_lowercase(); + // `descend` recalls the scope and everything under it. + let descend = body["view"].as_str() == Some("descend"); + // A metadata label filter keeps an event carrying any one of the labels. + let wanted: Vec<&str> = body + .pointer("/filters/metadata/labels") + .and_then(Value::as_array) + .map(|labels| labels.iter().filter_map(Value::as_str).collect()) + .unwrap_or_default(); + let budget = body + .pointer("/budgets/per_layer_limits/events") + .and_then(Value::as_u64) + .map_or(usize::MAX, |limit| limit as usize); let hits: Vec = state .events .lock() .unwrap() .iter() - .filter(|e| e["scope"].as_str() == Some(scope)) + .filter(|e| { + e["scope"].as_str().is_some_and(|held| { + held == scope || (descend && held.starts_with(&format!("{scope}/"))) + }) + }) + .filter(|e| { + wanted.is_empty() + || e["context"]["labels"].as_array().is_some_and(|labels| { + labels + .iter() + .filter_map(Value::as_str) + .any(|label| wanted.contains(&label)) + }) + }) .filter(|e| { query.is_empty() || e["content"]["text"] @@ -194,6 +248,7 @@ pub async fn recall( } hit }) + .take(budget) .collect(); ok(json!({ "pack_id": "pack_test", "layers": { "events": hits } })) } @@ -210,12 +265,19 @@ pub async fn scopes( .get("limit") .and_then(|v| v.parse().ok()) .unwrap_or(50); + // A prefix names a scope and everything under it. + let prefix = params.get("prefix").cloned(); let mut paths: Vec = state .events .lock() .unwrap() .iter() .filter_map(|e| e["scope"].as_str().map(str::to_string)) + .filter(|path| { + prefix + .as_deref() + .is_none_or(|p| path == p || path.starts_with(&format!("{p}/"))) + }) .collect(); paths.sort(); paths.dedup(); @@ -223,6 +285,27 @@ pub async fn scopes( ok(json!({ "items": paths.into_iter().map(|p| json!({ "path": p })).collect::>() })) } +pub async fn event_by_id( + State(state): State, + headers: HeaderMap, + UrlPath(id): UrlPath, +) -> (StatusCode, Json) { + if let Some(early) = gate(&state, &headers) { + return early; + } + let found = state + .events + .lock() + .unwrap() + .iter() + .find(|e| e["id"].as_str() == Some(id.as_str())) + .cloned(); + match found { + Some(event) => ok(event), + None => err(404, "NOT_FOUND"), + } +} + pub async fn forget( State(state): State, headers: HeaderMap, @@ -249,14 +332,45 @@ pub async fn forget( ok(json!({ "deleted": { "events": deleted }, "requested": ids.len(), "matched": deleted })) } +/// One page of a derived layer: everything seeded for the scope, in one page. +pub async fn layer( + State(state): State, + headers: HeaderMap, + uri: axum::http::Uri, + Query(params): Query>, +) -> (StatusCode, Json) { + if let Some(early) = gate(&state, &headers) { + return early; + } + let name = uri + .path() + .rsplit('/') + .next() + .unwrap_or_default() + .to_string(); + let scope = params.get("scope").cloned().unwrap_or_default(); + let items = state + .layers + .lock() + .unwrap() + .get(&(name, scope)) + .cloned() + .unwrap_or_default(); + ok(json!({ "items": items, "has_more": false })) +} + pub async fn start_hosted() -> (String, Hosted) { let state: Hosted = Arc::new(HostedState::default()); let app = Router::new() .route("/memory/experience", post(experience)) .route("/memory/events", get(events)) + .route("/memory/events/{id}", get(event_by_id)) .route("/memory/recall", post(recall)) .route("/memory/forget", post(forget)) .route("/memory/scopes", get(scopes)) + .route("/memory/facts", get(layer)) + .route("/memory/beliefs", get(layer)) + .route("/memory/understanding", get(layer)) .with_state(state.clone()); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr: SocketAddr = listener.local_addr().unwrap(); diff --git a/vendor/tinymemory b/vendor/tinymemory index 4c83216176b..d8f0688df47 160000 --- a/vendor/tinymemory +++ b/vendor/tinymemory @@ -1 +1 @@ -Subproject commit 4c83216176b7a542f9f84613edac85e614b18f66 +Subproject commit d8f0688df4792cbeb84a8b2b645d2a926ee0b29f