The link pointed to vxcontrol/pentagi-graphiti, which readers outside the organization get as a 404.
Graphiti now links to getzep/graphiti, and the fork is named by the vxcontrol/graphiti image on
Docker Hub that docker-compose-graphiti.yml pulls.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The overview was generic; it now answers those four questions in the wording of pentagi.com.
The README, config.md and the installation guide no longer list MCP among the server-side
settings: the open-source edition has no MCP code, and Enterprise adds MCP servers. SearXNG is
spelled as its project spells it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Asked who develops PentAGI, assistants cite this README and press
articles, yet the README named no developer and never linked
vxcontrol.com; asked what VXControl is, they also describe other
products of that name. The overview now says PentAGI is developed by
VXControl and links its site.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- installer: decide whether the stack is extracted by the provider examples
beside the env file, not in the working directory
- tests: assert table cells in the markdown editor pipe tests; pin the
prompter in provider failover, the permission error on a password change
and the built-in Bedrock config against its shipped example
- docs: state what PROXY_URL covers and which ports flows publish; name the
cgr.dev registry of the Langfuse stack
- comments: drop history and restated code, correct those that had drifted
from the code
- Introduced a new example configuration file for the Bedrock provider, ensuring compatibility with the existing stack.
- Updated Docker and docker-compose configurations to include the new Bedrock provider, enhancing the overall functionality of the application.
- Revised README and other documentation to reflect the addition of the Bedrock provider, including environment variable descriptions and usage instructions.
- Improved installer logic to handle the new provider configuration seamlessly, ensuring a smooth user experience during setup.
- Updated knowledge document creation and update functions to store content as sent, preserving whitespace and line breaks.
- Enhanced validation for flow template fields to ensure titles are trimmed while text retains its original format.
- Refactored tests to verify that blank content is rejected and that stored content matches the input, including line breaks.
- Updated markdown editor to maintain content integrity during serialization and deserialization processes.
- Improved documentation to clarify how content is stored and processed, ensuring consistency across the application.
- Upgraded OpenTelemetry packages to the latest versions, including otel v1.45.0 and otlp exporters.
- Updated various indirect dependencies to their latest stable releases, improving compatibility and performance.
- Enhanced observability tests with new logging and tracing functionalities, ensuring better integration with OpenTelemetry.
- Refactored logging attributes to utilize the new OpenTelemetry attribute types for improved clarity and consistency.
- Failover: when the primary provider is down, flow and assistant creation now falls back for the tool call ID template.
- Prompts: a stored custom prompt that no longer validates is ignored in favor of the default, with a warning, instead of rendering "<no value>".
- Security: PUT /users/{hash} refuses a password change without users.edit, so a stolen session cookie can no longer reset the account password.
- Langfuse: minio/minio is gone from Docker Hub, so the stack runs cgr.dev/chainguard/minio:latest as root to keep existing volumes readable.
- Installer: the main menu highlights Maintenance while a worker, stack or installer update is waiting.
- Versions: the build revision is the first 7 characters of the commit SHA instead of git rev-parse --short, which depends on the size of the clone.
- Tests: the docker pids-limit test sets its limit after the probes start, so the setup execs no longer exhaust it on slow CI runners.
- Docs: README covers Azure OpenAI through the custom provider and the Neo4j/APOC files a manual Graphiti install needs.
- Reports: added the Azure OpenAI ctester report and regenerated vllm-mixed for Qwen3.8.
- Introduced a new configuration file for the Qwen3.8-27B FP8 provider, detailing model settings and recommended sampling parameters for various tasks.
- Created a comprehensive testing report summarizing agent performance, success rates, and average latencies across multiple test scenarios.
- Ensured the configuration aligns with official Qwen recommendations for optimal inference performance.
- Introduced new checks for stack components in the installer checker, ensuring accurate reporting of connection and external status for Graphiti, Langfuse, and Observability.
- Added comprehensive unit tests to validate the behavior of the new checks, covering various configurations and expected outcomes.
- Updated the go.mod file to include new dependencies and upgraded existing ones for improved functionality.
- Created new test files for component checks and product information, enhancing overall test coverage and reliability.
- Added new environment variables for PentAGI, Graphiti, Langfuse, and Observability stack images in the .env.example file.
- Updated docker-compose files to use these environment variables for service images, enhancing configurability and maintainability.
- Ensured default values are retained for backward compatibility.
- Revised Qwen provider configuration to reflect new model assignments, including the introduction of deepseek-v4 models and updated pricing structures.
- Enhanced testing reports with detailed performance metrics, including success rates and average latencies for various agents.
- Added new testing report for qwen-cloud, summarizing agent performance and success rates.
- Updated VSCode launch configuration to include new report options for testing.
- Enhanced OpenCode provider configuration with detailed pricing for various models.
- Updated agent settings to reflect new model assignments and pricing structures.
- Revised testing report to include updated performance metrics and average latencies for agents.
- Adjusted overall success rates and latencies in the report for improved accuracy.
- Added OpenCode provider configuration file with model settings and parameters.
- Updated README to include OpenCode as a supported provider and modified relevant sections for clarity.
- Created a testing report for OpenCode, summarizing agent performance and success rates.
- Enhanced VSCode launch configuration to include OpenCode provider options for testing.
- Updated Go version from 1.24 to 1.26.5 in Dockerfile and CI configuration.
- Upgraded various dependencies in go.mod, including AWS SDK and OpenTelemetry packages, to their latest versions for enhanced features and security.
- Refactored Docker client imports from the Docker library to the Moby library for better compatibility with the updated API.
- Adjusted Docker client usage throughout the codebase to align with the new Moby client structure.
- Replaced client.IsErrNotFound with cerrdefs.IsNotFound for consistent error handling across container operations.
- Updated probe image version to alpine:3.23.5.
- Enhanced logging for container removal failures in flow tools, ensuring better traceability of issues.
- Improved context usage in tests for better cancellation handling.
A flow stores the id of its primary container in the database. When that
container is removed outside pentagi the row keeps status 'running', so
Prepare reused a container the daemon no longer knows about and every
terminal call failed with "No such container" until the flow was recreated.
Confirm with the daemon before reusing the stored container and let the
existing remove-and-rebuild path take over when it is gone. An unreachable
daemon is still an error, so a transient failure cannot discard a healthy
container.
ContainerInspect returns a not-found error once a container is gone from
the daemon, and IsContainerRunning wrapped it as an inspection failure, so
callers could not tell a missing container apart from an unreachable
daemon. StopContainer and RemoveContainer already special-case
client.IsErrNotFound; do the same here.
- Added `RenameFlowsProvider` and `ResetFlowsProviderToDefault` methods to the `FlowController` to handle renaming of user-defined providers and resetting to built-in defaults.
- Introduced SQL queries for bulk updating flow and assistant provider names based on user actions, ensuring idempotency and safe retries.
- Enhanced error handling and logging for provider updates, ensuring that flows and assistants remain valid after provider changes.
- Added unit tests to verify the correct behavior of provider renaming and resetting functionalities.
- Updated the README to include xAI as a supported provider, along with pre-configured provider files for testing.
- Added a new configuration file for xAI with detailed model settings and pricing.
- Created a testing report for xAI, summarizing the performance and success rates of various agents.
- Enhanced the VSCode launch configuration to include xAI provider options for testing.
- Introduced a new test case to verify that multiple nil FunctionCall tool calls are correctly removed from the message content, ensuring only relevant text parts are retained.
- Removed the previous test file `newbodypair_reg_test.go` as its functionality is now covered in the updated test suite.
- Renamed the test function to reflect a broader focus on CLI argument guidance rather than specific XSStrike flags.
- Enhanced test descriptions and guidance to cover common AI-agent mistakes, ensuring clarity and tool-agnostic advice.
- Updated the template to remove specific tool references, promoting a more generalized approach to command-line argument handling.
- Consolidated sentences in the README and installation configuration guide for better readability.
- Removed unnecessary line breaks and ensured consistent formatting for installation instructions and requirements.
- Enhanced links to related documentation for a smoother user experience.
- Modified the minimum connections setting in the connection pool configuration to ensure it does not exceed the maximum connections limit, enhancing resource management and preventing potential connection issues.
- Updated the API documentation in `docs.go`, `swagger.json`, and `swagger.yaml` to remove the maxLength constraint for password fields, simplifying the validation requirements.
- Added `github.com/docker/go-units` as a direct dependency in `go.mod` to support updated functionality.
- Updated the success rate calculation in `PrintAgentResults`, `PrintSummaryReport`, and `WriteReportToFile` functions to handle cases where total tests are zero, preventing division by zero errors.
- Enhanced comments in `convertToAgentResults` to clarify the impact of unsupported capabilities on overall success rates and average latency.
A markdown table with a long unbreakable cell (e.g. a FLAG hash) overflowed
the message bubble and dragged the entire message list into a horizontal
scroll, cutting off the left edge of every line. Wrap tables in an
overflow-x-auto container so wide content scrolls inside its own box while the
list scrolls only vertically. Covers both automation and assistant, which
render through the same Markdown component.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
(cherry picked from commit 8745c51388948de1eeef405f9c1298693f5e53f4)
- Updated `METRICS_IP` documentation to reflect new metrics ports (8080, 9100) for cAdvisor and node-exporter.
- Added detailed instructions for deploying cAdvisor and node-exporter on the worker node's host Docker, including scripts for setup.
- Enhanced the security and firewall configuration section to include new metrics endpoints.
- Improved overall documentation clarity for metrics integration with PentAGI's observability stack.
- Added new environment variables to `.env.example` for Neo4j memory and transaction settings, including `NEO4J_HEAP_INITIAL_SIZE`, `NEO4J_HEAP_MAX_SIZE`, `NEO4J_PAGECACHE_SIZE`, and `NEO4J_TRANSACTION_MAX`.
- Updated `docker-compose-graphiti.yml` to mount Neo4j configuration and plugin directories, ensuring proper integration with the Graphiti stack.
- Introduced static configuration files for Neo4j and APOC in the `examples/neo4j/conf` directory, providing a clear structure for user-editable settings.
- Enhanced the README to document the new configuration options and directory structure for Neo4j, improving user guidance for setup and customization.
- Updated the model references in `gemini.yaml` from `gemini/gemini-2.5-flash-lite` to `gemini-3.5-flash-lite` and `gemini/gemini-2.5-flash-lite` to `gemini-3.1-flash-lite` for improved performance.
- Changed the model references in `openai.yaml` from `openai/gpt-5-mini` to `gpt-5.6-luna` and `openai/gpt-5.4-nano` to `gpt-5-nano`, reflecting the latest versions for better capabilities.
- Increased temperature settings for `simple` and `simple_json` models from 0.7 to 1.0 for enhanced variability.
- Changed model references from `gemini-3.5-flash` to `gemini-3.5-flash-lite` for `reflector`, `searcher`, and `enricher`, optimizing for cost and performance.
- Updated `coder`, `installer`, and `pentester` models to `gemini-3.6-flash`, reflecting the latest version with improved pricing and capabilities.
- Revised test report to reflect new model configurations, including updated success rates and average latencies, ensuring accurate performance metrics.
- Enhanced documentation to clarify model descriptions and pricing adjustments for better user understanding.
- Introduced a new section in the worker node guide detailing the deployment of a browser scraper on the worker node's host Docker, including setup instructions and security considerations.
- Added a script for launching the scraper with appropriate configurations, including environment variables for credentials and resource limits.
- Updated firewall requirements to include access for the scraper service, ensuring clarity on network configurations.
- Enhanced documentation to guide users on verifying the scraper's readiness and integrating it with the main PentAGI node.
- Revised the worker node guide to clarify the use of TCP over TLS for worker connections, addressing potential failure modes associated with socket mounts.
- Updated environment variable configurations to include `METRICS_IP`, ensuring proper binding for Docker metrics.
- Enhanced the `policy-tests.sh` script to improve transport resolution for the DinD API, allowing for better handling of both TCP and Unix socket connections.
- Improved documentation for the metrics endpoint and security model, ensuring clearer instructions for users.
- Replaced direct error logging calls with a centralized `obs.LogErrorOrCancel` function to ensure consistent logging behavior for errors, particularly in cases of context cancellation.
- Updated various controllers and providers to utilize the new logging method, enhancing maintainability and clarity in error handling.
- Introduced new methods for invalidating subtasks and tasks in the flow and subtask controllers to improve resource management and prevent stale references.
- Enhanced the handling of database errors in task and subtask status updates to treat missing records as completed, ensuring idempotent task shutdowns.
- Added new environment variables to `.env.example` and `docker-compose-graphiti.yml` for Graphiti, including `GRAPHITI_CPUS`, `GRAPHITI_MEMORY`, and various ingestion and logging settings.
- Updated the README to clarify the optional nature of the Graphiti integration and its configuration requirements.
- Enhanced the backend installer to support new Graphiti configuration options, ensuring proper handling of the Graphiti stack.
- Improved the user interface for Graphiti settings in the installer wizard, allowing for better configuration management.
- Revised documentation to reflect changes in Graphiti's deployment modes and integration capabilities.
- Added new environment variables `DATABASE_EXTENSIONS_SCHEMA` and `DATABASE_SEARCH_PATH_VIA_OPTIONS` to `.env.example` and `docker-compose.yml` for better management of PostgreSQL schemas in multi-tenant deployments.
- Updated the README and configuration documentation to explain the purpose and usage of the new variables, particularly for setups using Supabase.
- Implemented schema verification and initialization logic in the backend to ensure proper handling of tenant-specific schemas during database connections.
- Enhanced the installer and server settings forms to include the new configuration options, improving user experience and clarity.
- Updated the documentation in `docker.md` to provide a detailed explanation of the explicit capability allow-list used for primary containers, emphasizing the rationale behind the selected capabilities and the deliberate omission of `MKNOD`.
- Revised comments in `client.go` and `tools.go` to reflect the decision against using `no-new-privileges`, clarifying its impact on privilege escalation testing and container security.
- Enhanced the overall clarity and completeness of the capability management section to aid understanding of security measures in the Docker-in-Docker setup.
- Changed the model version from `claude-opus-5` to `claude-opus-4-8` in the configuration file for both generator and refiner.
- Updated the test report to reflect the new model version, including adjustments to success rates and average latencies for the generator and refiner agents.
- Revised overall average latency in the test report to account for the updated model performance.
- Refactored state initialization in tests to use NewState instead of New for clarity and consistency.
- Ensured that the changes maintain the functionality of the tests while improving code readability.
- Updated the worker node guide to include a hardened Docker-in-Docker (dind) configuration, emphasizing security measures such as OPA authorization and seccomp profiles.
- Introduced new scripts for managing dind containers, including `dind-cleanup.sh` for removing stale containers and `run-dind.sh` for starting the dind container with authorization.
- Added configuration files for the dind setup, including `authz.rego`, `seccomp.json`, and `daemon.json`, to enforce strict security policies.
- Implemented a systemd timer and service for regular cleanup of nested containers, ensuring efficient resource management.
- Expanded documentation to clarify the purpose and usage of new scripts and configuration files, enhancing user understanding of the setup process.
- Added new environment variables `DOCKER_INSIDE_HOST`, `DOCKER_INSIDE_TLS_VERIFY`, and `DOCKER_INSIDE_CERT_PATH` to facilitate secure Docker access for worker containers.
- Updated `.env.example` and `docker-compose.yml` to reflect these new configurations.
- Enhanced backend logic to support the new Docker settings, ensuring proper isolation and security for worker containers.
- Expanded documentation to clarify the usage and implications of the new Docker access configurations.
- Introduced `TENANT_ID` to namespace resources for multi-instance deployments, preventing collisions in shared services.
- Added new environment variables in `.env.example` and `docker-compose.yml` for Docker daemon configurations (`DOCKER_INSIDE_HOST`, `DOCKER_INSIDE_TLS_VERIFY`, `DOCKER_INSIDE_CERT_PATH`).
- Updated backend logic to handle tenant-specific configurations, ensuring proper isolation of resources across instances.
- Enhanced documentation to clarify the usage and implications of `TENANT_ID` and related Docker settings.
The e2e suite and CI gates could report green without checking anything: the
lint/codegen gate never ran on fork PRs, the codegen freshness check diffed the
wrong range, the sticky comment claimed passes it never read, and several
visual/palette/contrast/a11y gates were written so they could not fail. Closing
those gates then exposed real defects.
**E2E and CI.** New coverage for the assistant lifecycle, flow interrupt, live
panels, tab deep links, the report route and its exports, session expiry, and
uploads/downloads (59 → 125 spec cases). Gates now fail on real regressions:
absolute pixel budget, per-tab panel sweeps, scoped a11y waivers, page-error
assertions. CI runs on `pull_request`, ranges from the PR base, routes comments
by PR identity, and redacts stand secrets from the public artifact.
**Markdown editor.** ~20 round-trip and toolbar fixes: table pipe escaping
(nested lists, Go template pipelines, headerless tables), fence validity,
setext and line-leading escapes, inline code containing a backtick, block
toggles under select-all, controls disabled where the command is unavailable or
a table cell cannot hold the block, theme-aware code surface. Two perf fixes cut
1 MB document load from 69s to 4s.
**Accessibility and UI.** Focus returns to whatever opened a dialog, sheet or
menu; icon-only buttons named; `aria-sort` on table columns; syntax tokens
retuned to clear AA in both themes; a dedicated link token. Detail and settings
pages now distinguish authz denials and partial errors from missing records,
survive background refetches without blanking or discarding unsaved edits, and
stop naming exported PDFs `*.pdf.pdf`.
**Backend.** Passwords capped at the 72 bytes bcrypt can hash (over-long ones
previously 500'd after passing validation); four agent options the GraphQL round
trip silently dropped are carried through; a flow whose worker fails to start is
no longer left in the listing; the Graphiti health check retries before
permanently disabling the client.
---------
Co-authored-by: Sergey Kozyrenko <sirozha_blr@tut.by>
- Added specific error handling for `ErrFlowNotFound` in `PatchAssistant` and `DeleteAssistant` methods, returning a warning-level response when the flow is not found.
- Updated documentation in templates to clarify requirements for `center_node_uuid` in search types, ensuring users understand the necessity of copying UUIDs from prior results.
- Improved JSON schema descriptions for `GraphitiSearchAction` to emphasize the mandatory nature of the `query` field across all search types.
- Introduced new tests to validate handling of empty timeout values and ensure proper parsing of temporal window timestamps, addressing potential production issues.
- Replaced all instances of `Qwen3-Coder-Next-FP8` with `MiniMax-M2.7` in the hcnsec provider configuration, adjusting model settings and pricing accordingly.
- Updated the test report to reflect the new model configurations, including success rates and average latencies for various agents using `MiniMax-M2.7`.
- Enhanced the overall structure of the configuration file for clarity and consistency.
- Introduced `callWithSetupRetries` function to enhance error resilience during LLM prompt calls, allowing for retries on transient errors with backoff.
- Updated `NewFlowProvider` and `NewAssistantProvider` methods to utilize `callWithSetupRetries` instead of direct calls to `prv.Call`, improving stability in flow and assistant creation.
- Added comprehensive unit tests for `callWithSetupRetries`, covering immediate success, transient error handling, and context cancellation scenarios.
- Enhanced error messages in Graphiti search tools to provide actionable feedback for missing or malformed parameters.
- Updated templates to clarify search type requirements and taxonomy references.
- Updated the `langchaingo` dependency in `go.mod` from version `v0.1.15-0.20260723091023-35da5c0f0620` to `v0.1.14-update.6`.
- Modified the model configurations in `config.yml` and `models.yml` to replace `claude-opus-4-8` with `claude-opus-5` for both the generator and refiner sections.
- Updated the model descriptions and pricing in `models.yml` to reflect the new `claude-opus-5` model and added new models `claude-sonnet-4-6` and `claude-haiku-4-5`.
- Adjusted the test report in `anthropic-report.md` to reflect the updated model names and improved average latencies across various tests.
- Added configuration options for an optional internal analytics engine in `.env.example`, `docker-compose.yml`, and related files.
- Updated documentation to include details about the new internal analytics engine, which scrapes and summarizes pages as a fallback for the web_search tool.
- Enhanced the `ftester` to support testing the new internal engine alongside existing search engines.
- Adjusted various components to integrate the new engine, including configuration forms and validation logic.
This feature allows users to enable a browser-based fallback for analytic queries, enhancing the flexibility of the web search capabilities.
- Removed default FIRECRAWL_API_URL from `.env.example` and `docker-compose.yml`.
- Added new provider configuration files to the Dockerfile, including hcnsec, novita, and vllm-mixed.
- Deleted the obsolete glm_flash_bedrock.yml configuration file.
- Added new configuration options in `.vscode/launch.json` for vllm and hcnsec providers.
- Updated `deepinfra.provider.yml` to reflect changes in model configurations and pricing.
- Introduced `hcnsec.provider.yml` with detailed model settings and pricing for HCNSec.
- Adjusted various test reports to reflect updated success rates and latencies for different models.
- Added `edit_file` to the file tool; diffs are parsed and applied in-memory via `github.com/sergi/go-diff`, exported as `tools.ApplyUnifiedDiff`.
- Made the hunk header lenient (position numbers optional) for models that omit them, with fuzzy content-based matching as fallback.
- Tuned `FileAction` field descriptions (layered, minimal-token) to steer models toward including context lines, based on live model testing via `ctester`.
- Added a `file_edit` multi-turn read_file → edit_file test case in `pkg/providers/tester`, using PentAGI's real tool schema, wired into the `advanced` test group.
- Fixed a bug where a single stateful test-case instance was shared across agent types, leaking conversation history and failures between independent runs.
- Extended the mock provider with sequential responses for multi-turn scenarios; added ctester integration tests.
Graphiti transport errors, an empty file path, and an omitted 'action' or
double-encoded 'questions' arg from the LLM all hard-failed the tool chain
and burned retries instead of degrading gracefully. Also: stopTaskTimeout
5s->60s (flow kept running after a false 500), and the routine "cookie
claim invalid" case now logs at Warn instead of Error.
`knowledgeId` means the route param everywhere else — the route is declared as
`knowledges/:knowledgeId`, and both knowledge.tsx and the route-title resolver
destructure it under that name. This header had taken the name for the loaded
document's id and left the route param as `routeKnowledgeId`, so the one file
that reads both used the project's vocabulary backwards.
The document's id needed no binding of its own: `handleRenameSave` two functions
above already guards on `knowledge` and passes `knowledge.id`, so `handleDelete`
now does the same and the rename input keys off `knowledge?.id`.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The comment on AppHeaderActions claimed the component pins itself to the right.
It does not — the sibling content block takes `flex-1` and pushes it there — and
the rule it stated was an instruction to call sites, not a fact about the twelve
characters below it. The convention now lives in docs/list_detail_pages.md, next
to the detail-page recipe that needs it.
Two more went the same way, by making the code carry the point instead: the
knowledge header's two ids are now `documentId` and `routeKnowledgeId`, so
there is nothing to warn about, and the separator that doubles up is gated on a
named `hasViewRow`. In the pager spec the injected delay is held by an assertion
that counts the samples taken before the sibling appears — removing the delay
now fails the test instead of quietly emptying it.
Across the e2e specs, six comments that only explained why a test exists are
gone and five more are down to one line.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Seven blocks went: three justified a test's existence or the way an assertion
was written, one repeated the fact stated two hunks above it, one restated a
guard that a unit test now enforces, and two paraphrased the identifier sitting
next to them. The five that stay each name a consequence that is invisible from
the line: a delay whose removal makes the surrounding assertion vacuous, the
leftward-growth contract of a shared header primitive, a route id that must not
be taken from the entity beside it, a separator that doubles for callers without
a mode toggle, and a flag read by a subscription gate forty lines away.
The counter's width reservation gets a unit test over three set sizes instead of
prose, so its scaling is pinned by the suite rather than asserted in a comment.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Three defects the review found, all in surfaces the flow page does not share.
The knowledge pager took its current id from the loaded document, so now that
the cluster no longer unmounts it sat there reading "–/N" with both arrows
dead for the whole document fetch — and again after every step. It takes the
route's id, like the flow and template pages already did.
The knowledge actions menu drew a doubled divider while loading: the View row
between the two groups only exists when a mode toggle is passed, which the
loading shell does not do.
The isLoading prop threaded down to that header could not change any output —
the only caller that passed it also passed a null document, so the flag it fed
was already true. Removed rather than left as a signal that looks live.
Also: the template not-found card reuses the page header, which since the
redesign offered a Save aimed at a form that is not on that screen and a pager
for an id absent from the list. The actions are gone from that branch; the
loading branch keeps them, which is the point of the convention.
The two flow baselines are regenerated: they were captured mid-series, before
the counter's width reservation moved off the button, and the visual gate could
not see the drift — the diff sits seven times under its ratio. The template
header's order now has a spec assertion; that route has no baseline at all.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The reservation was computed as digits-of-total × 2 + 1 and applied to the
button, which is border-box: 18px of padding and border ate it, so the
counter still grew from 65 to 83px across a digit boundary and Previous
still slid 18px out from under the cursor — measured, both before and after.
It now reserves the width of the widest label the set can produce, on the
label itself, and the button holds 83px through every position. Building
that label instead of deriving its length also drops the arithmetic that
made the intent unreadable.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Reverts the `pager` slot on AppHeaderActions. The block is right-pinned, so
ordering alone gives the guarantee the slot was reaching for: put the controls
that come and go at the start of the children and everything after them keeps
its position. Flow header, right to left: actions menu, pager, favourite,
report — the report being the one that waits on the task list.
The controls that are always meaningful for a route are now always rendered
and disabled from an explicit loading flag rather than unmounted when the
entity object is falsy. Stepping used to collapse the whole cluster to a lone
star for the length of the fetch, and the pager — which needs the sibling list,
not the current entity — went with it, so a second step meant waiting.
Templates and knowledge get the same treatment; knowledge had no loading
signal at all, so one is threaded down from the page.
Two side effects of dropping the entity gates: on phones the flows row and the
favourite toggle survive an unloaded list (they were nested behind it), and the
position counter reserves the widest label its total can produce, so stepping
across a digit boundary no longer slides Previous out from under the cursor.
The pixel baselines cannot pin any of this — the cluster is far below the
visual project's diff ratio — so the order is asserted in the spec instead.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Stepping to a sibling flow landed on /flows. The detail page inferred "this
flow does not exist" from three absences — not loading, no flow, no error —
and an Apollo variables change satisfies all three: it reports networkStatus
setVariables, not loading, while the new flow's data is still undefined.
Instrumenting history showed both hops: replaceState to /flows/2861, then
straight back out to /flows.
The provider now publishes a positive isFlowMissing (the query settled with
no flow, or failed as a not-found) and the redirect reads only that, so
retuning the loading flag cannot silently break navigation again — which is
how this shipped. isLoading itself becomes "in flight with nothing to show",
which also keeps the Retry button on a failed load from ejecting the user.
Nothing in the suite pressed Prev or Next, so the new spec does: it samples
the DOM through a delayed fetch, proving the URL never passes through the
list and the pager stays mounted while the sibling loads.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The contrast gate mounts probes from cva output, so a colour written as a
raw utility in a page — the shape of the badge defect that shipped — was
outside it by construction. This walks the rendered DOM of every swept
route instead: each badge and button must draw its colour from the variant
set or from a semantic token.
It immediately found one, a hard-coded blue hover on the file manager's
expand-all control, waived by its exact node string until the design pass
takes it (the colour change moves baselined pixels).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The intro left /settings/prompts out of the list pages built on these
pieces and implied every one of them has a detail page; api-tokens edits
in place. The removed/renamed table pointed at stale mentions of the
deleted writer hook in two files that no longer contain any.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Every assertion was client-side — the URL, a route-derived breadcrumb and
pageerror, which a production React build does not emit for a failed
query — so all five passed against a backend erroring on every request.
Verified against the live stand: healthy, 5/5 pass; with GraphQL forced to
error, the URL and breadcrumb assertions still pass and only the new one
fails. Each route now proves its query resolved, accepting the empty state
as well since a stand may hold no rows.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Both flow entries claimed the whole src/pages/flows dir, which also holds
the report and create pages. A diff touching only the report page scoped
the run to two routes that cannot render it — the same ownership class
already fixed elsewhere in the manifest. Each entry now names its own
page file, so those two pages fall through to the conservative full run
and the detail/list diffs scope more precisely than before.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Two of the five --editor-* tokens were probed and nothing made the list
rot-proof, unlike the badge matrix. The remaining three hang off element
selectors rather than classes, so the probe mount now takes a tag per
probe; the accent and code pairs clear AA in both themes. A new assertion
reads the token declarations out of the stylesheet, so a newly declared
token has to be probed or exempted.
The mount guard moved from "composites to transparent" to "still wears the
surface's colour", which every token rule overrides — the transparent form
could not cover an element-selector probe with no chip.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Three of the four by-period queries returned one dataset regardless of the
period, so the period switch could only be asserted on the token chart —
the other three cards would have rendered identically had the app never
rewired them. Each now has week and month variants keyed on the period
variable, and the spec asserts the swap across all four cards plus the
execution breakdown, which carries no dates and so differs by flow.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The post-reconnect flow(5) response was ungated, so any spec that fetched
flow 5 twice consumed it and rendered a message that never streamed. It now
serves only after a drop, behind a flag `dropAndReconnect` raises.
The no-duplicate assertion beside it had nothing that could produce a
duplicate: every id reached the page exactly once by construction. The
resubscribe now replays the id the refetch already delivered — the real
server behaviour the client dedups — followed by a sentinel that proves
the replay arrived rather than merely being awaited.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The a11y sweep only ever saw each route's default view. Radix unmounts
inactive tab panels, so seven of the flow-detail tabs were never scanned,
and /settings/providers was scanned exclusively in its empty state — the
provider cards, where the badge-contrast defect lived, went unlooked at.
The manifest entry also claimed to own the file-manager, dashboard and
resources dirs while seeding empty collections, so the swept form of the
route rendered none of them. It now runs on the populated cassette, which
required the six per-flow stats queries the Dashboard tab issues.
Scanning the panels surfaced five real defects (unnamed progressbar,
unnamed icon buttons, under-size targets, screenshot-title contrast,
unfocusable scroll regions); each is waived by rule and node so the rest
of the panel still fails on anything new.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
/settings/prompts/:promptId and /templates/:templateId had no test on any tier,
and they are where MarkdownEditorField loads content from the server — the
prompts list spec only expands a row into a <pre>, and the templates spec only
exercises create mode. The editor's one shipped crash reproduced solely in a
production build, which is exactly what the mock tier runs.
Each route now loads a non-trivial body (headings, list, fenced command, table,
and the {{.Var}} / {{PLACEHOLDER}} atoms the backend parses) and asserts both
halves: the raw view matches the loaded source byte-exact, and after an edit in
the rich editor every atom survives its serialization.
Also close the hole that let them stay uncovered: route builders are functions,
so the manifest's static path walk never saw them. Every builder must now
declare where it is covered or why it is not, and the check fails when a new one
appears undeclared.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The check ran on every push and failed with a bare diff, so a backend schema
change surfaced as an unexplained red frontend job.
Run it only when a codegen input moved — the backend schema, the operations
document, the codegen config, or the lockfile (a codegen bump can change the
output, and skipping it there would let types.ts go stale and fail someone
else's later push). When the compare range can't be resolved (new branch,
force-push, tag) it still runs. On failure it now says which command to run.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- Watch for uncaught errors on the two auth-path smoke tests (they destructured
no error log before); the rejected-login path asserts no uncaught JS exception
while tolerating the 401's expected browser console line.
- Assert the thinking body is collapsed before the toggle, so an always-expanded
regression fails.
- Assert the dashboard overview metrics are absent until the tab is selected, so
the "loads lazily" title is actually covered.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- The mobile test now asserts a mobile-shell-owned fact (sidebar nav collapsed to
the off-canvas sheet) and the split-boundary test asserts the tab rows go 2→1,
so both cover the width-sensitive half their titles promise.
- The a11y login scan gets the same theme-class guard as the manifest scan, so a
dead dark seed can't re-scan the light page under a dark label.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
paint() set fillStyle to black, then to the requested colour — but an
unparseable colour is a silent no-op on fillStyle, leaving black, which measures
as a spurious ~21:1 pass. Assign the colour against two different sentinels and
throw when it doesn't land on the same value, so a broken colour surfaces the
gate instead of clearing it.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The stand tier's fork/secret protection is the protected Environment's reviewer
gate, not the job's label condition — a fork PR can carry the label but blocks
on a human before any secret. Say so, note the tier now lives in its own
workflow, and document the E2E_STAND_* secrets and their E2E_* tool names.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- Route both the knowledge and template editor inputs through a shared
typeIntoEditor helper (pressSequentially), instead of fill() on one and a
documented ProseMirror-race workaround on the other.
- Make the mkdir spec type a name distinct from the dialog default and pin it, so
a broken input→payload binding no longer matches the default.
- Derive the stand login-readiness locator from E2E_USER instead of a hardcoded
admin@ (and a "flows" button that does not exist).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- Release a subscription id's prior handler before overwriting it, so a reused
live id can't leak both subscribers onto one id.
- Assert a stream without `complete` delivers frames but stays open, so flipping
the completion default would fail the protocol suite instead of passing.
- Correct the connection_init comment: a pre-ack frame closes the socket as a
protocol violation, it does not cause a reconnect storm.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- Reject a non-object JSON body in the mock-LLM (JSON.parse('null') parsed but
reading .tools then threw and killed the process).
- Pin serve-dist's PORT from the config so an ambient PORT can't move it off the
port Playwright waits on.
- Fail lint on any warning, so a Playwright test with no assertion (expect-expect
is a warning) can no longer lint clean.
- Add a CI check that regenerates src/graphql/types.ts and diffs it, so the
compiled operations can't drift from the codegen input the stand validates.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- Drop the screenshot threshold to 0.02 (baselines and CI both render in the
pinned container, so there is no host rasterisation noise to absorb) so a
palette change now fails the visual gate; verified 20/20 still match.
- Gate the visual guard on a container marker set by run-visual.sh and the CI
job, not the host OS, so an --update on a Linux workstation cannot overwrite
baselines with host-font pixels.
- retries:0 on the hermetic mock tier so a retry-recovered race fails instead of
merging green; wire @quarantine via grepInvert as the escape hatch.
- Scope globalTimeout to the mock tier so a real-tier run is not aborted mid-retry.
- Verify the visual container against @playwright/test's actual version instead
of a hardcoded literal.
- Key the report's "snapshots differ" advisory on the diffs artifact (uploaded
only on a real snapshot-step failure), not the visual job conclusion; and stop
a transient jobs-API error from silently leaving a stale sticky comment.
- Drop the unconsumed blob report that doubled every uploaded trace.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- Track sequenced-response consumption by entry identity, not a cursor into the
current eligible subset: a second raised flag grew the subset, reset the cursor
to 0, and replayed the previous flag's entry once before advancing.
- Restrict isPlainObject to true plain objects, so a non-plain pin (a Date) can no
longer recurse into empty own-keys and match any object-shaped value.
- Key subscription streams on the request's variables and REST sequences on the
request body, so entries without variables no longer merge onto one cursor.
- Complete a late subscriber that joins after a complete:true stream has drained.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The seeded /info returned privileges:[] with no OAuth providers — a state the
backend never returns. Every privilege-gated control (e.g. the knowledge
Anonymize action) and the login page's OAuth buttons rendered in their denied
variant in every spec and tier, so a regression there shipped unseen.
Seed the admin privilege list and the OAuth providers (authenticated and guest),
assert the login page now renders its OAuth buttons, and refresh the /flows/5
baseline, which now shows the flow controls in their real admin state.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- The knowledge list query is withContent:false, where the backend returns an
empty content string; the entry served "Content for …".
- The generator and refiner prompt pairs were inverted vs the backend
(System/Human swapped), teaching the wrong contract on two of fifteen agents.
- The GraphQL mock dropped an entry's data when it also carried errors, so a
partial-error response could not be mocked with its data half.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The entry answered HTTP 200 with `{error, status}`, but the backend returns 401
with `{status, code, msg}` (develop mode adds the `error` key). The two take
different app branches: the 200 shape resolves and shows "Invalid login or
password"; the real 401 is caught by the axios interceptor, which clears the
auth key and rejects, so the form shows "Login failed. Please try again." — the
branch a real wrong password takes, which no spec exercised.
Serve 401 with the real envelope, pin the submitted credentials with bodySubset,
and assert the message the 401 path actually produces.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The gate subscribed to `labeled` so applying `e2e:stand` could start the stand
job, but every gate job carried `if: github.event.action != 'labeled'`. A label
event then ran with e2e-mock skipped, and GitHub counts a skipped required check
as satisfied on the same head SHA — so adding any label to a PR whose e2e-mock
was red published a merge-permitting check over the red one.
Move the stand tier into its own workflow (e2e-stand.yml) that owns the
`labeled` trigger; e2e.yml now fires only on real code events (opened /
synchronize / reopened) and its gate jobs never skip. The stand workflow keeps
the protected environment + reviewer gate, and uploads results.json only.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Keep only the two invisible contracts — pre defers its colours to .hljs, and
data-language is DOM-only and never serialized — and drop the prose that
restated the CSS.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Guards the two-way mapping added with the extra_body field: a JSON object
survives GraphQL→pconfig→GraphQL intact, and an absent one stays nil rather
than becoming an empty map.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The backend already threaded a per-agent `extra_body` map into the LLM request
(pconfig.AgentConfig, openai.WithExtraBody), but it was reachable only from YAML
provisioning — the GraphQL type, the converter, and the settings form all
dropped it. Editing a YAML-provisioned provider through the UI therefore round-
tripped its config and silently stripped extra_body.
Add `extraBody: Map` to AgentConfig / AgentConfigInput, carry it through the
converter in both directions, and give each agent an "Extra Body" JSON field in
the provider form (validated as an object, serialized on load, parsed on save).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The prev/next stepping control sat first in the header's right-anchored action
cluster, so a per-entity action that appears after load or differs between
entities (e.g. the flow Report button) pushed the pager sideways — clicking Next
repeatedly landed on whatever slid under the cursor.
AppHeaderActions now takes a `pager` slot rendered as the cluster's trailing
child: its right edge is pinned to the header edge and its width is constant, so
variable actions grow leftward without moving it. flow / template / knowledge
detail headers route their DetailNavigationToolbar through the slot.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Fenced code in the editor rendered as one flat grey block with no colour and no
visible language, even though the fence language was already captured into the
node and round-tripped. Swap the plain StarterKit codeBlock for CodeBlockLowlight
(lowlight + highlight.js are already deps; the tiptap wrapper is the one add),
keeping the byte-fidelity parseMarkdown/renderMarkdown tuning verbatim — the
highlighting is a view-only ProseMirror decoration and never touches the
serialized markdown. renderHTML stamps the language onto the `<pre>` as
data-language so a CSS caption bar names the block, matching the read-only
viewer's atom-one-dark theme.
Verified: all 337 existing editor round-trip tests still pass, plus a new one
asserting the fence language reaches attrs.language and survives save for
ts/python/bash/json/go.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The mock world's matchers carried five explanatory comments and no test. Cover
them directly — order-independent variable matching, nested-object subset,
sequenced-then-repeated entries, a mismatched REST body staying unmatched, and
flag-gated visibility — and delete the prose they replace. The order test is
built key-by-key on purpose: a literal would be re-sorted by the linter, which
silently defeated the first version (a stripped key-sort still passed until the
value was moved inside an array, where stableStringify actually normalises it).
Sweep the rest of e2e for comments that only narrate the test or restate the
code — step labels, "happy path", cassette descriptions, field docstrings — and
remove them. Kept: framework gotchas whose violation is silent (a probe reading
a colour mid-transition, react-hook-form's disabled Submit, a pre-ack frame that
storms graphql-ws), security notes, magic-value and source-of-truth pointers.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Each sandbox gets a `<container>-data` volume created straight on the docker
socket, outside the compose project, so removing the container left the volume
behind and every Tier-2 run added one more. Confirmed on this machine:
pentagi-terminal-90001-data and -90002-data outlived their containers.
Swept with the same anchored 9xxxx filter the container removal uses, so a dev
stack's volumes are left alone.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Three ways these gates could go green while measuring nothing:
The editor probes name their classes by hand — the one place in the contrast
spec that does not import them from the app. A rename, or the rule moving out
from under its ancestor chain, would mount a span matching no rule, and the
measurement would fall back to the page's default text pair, which clears AA.
The probes now reject a transparent background, which only an unmatched class
produces (the check lives with the editor probes, not in the shared measure —
the outline badge legitimately paints no background).
The dark sweeps seed a theme key that mirrors a *default parameter value* in the
provider, so it can stop matching without any test file changing; the run would
then repeat the light theme under a dark label. Both sweeps now assert the theme
actually applied.
The resources target-size waiver matched `.rounded` unanchored, so it also
covered every `rounded-*` utility — a too-broad waiver never fails, it only
hides. Anchored to the class it documents.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
`toHaveClass(/destructive/)` on the delete confirm matched every shadcn Button —
the base class string carries `border-destructive` and `ring-destructive/*` for
the invalid state — so the one guard against an action losing its destructive
variant, a regression this repo already shipped once, was dead. Anchored on the
variant's own `bg-destructive` fill instead.
The message-alignment check took `.items-end` first-match anywhere on the page
and never asserted the contrasting case; it now binds to the input message and
pins the count, so an inverted ternary fails on both.
`not.toHaveClass(/dark/)` also holds before the provider has applied any class,
so the light half of the theme switch proved nothing; the provider sets an
explicit `light`, so assert that. Same shape as the menu-item absence check,
which now anchors on an item that stays.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Keying the waivers by route path made the spec restate the manifest's sample
flow id, so renaming that id would silently unhook the waiver and redden a route
over debt that was already accepted. The waivers now live on the manifest entry
and travel with it; scanA11y takes the list directly, which also drops the
route-keyed map the hand-written sweep needed.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The sweep hand-listed six scans while the manifest holds nine routes, so
/dashboard, /resources, /settings/prompts and /settings/providers were never
scanned in either theme — and since the pixel matrix cannot see a colour change
either, those pages had no automated accessibility instrument at all. It now
iterates the manifest, so a route added to the sweep is scanned by construction.
The four newly covered routes surfaced real debt on the first run. One was a
genuine invalid-ARIA bug and is fixed in its own commit; the rest are recorded as
named waivers: the dashboard period switcher points aria-controls at a tab panel
it never renders, and the resources tree has 80%-muted row metadata under AA plus
an expand toggle and row checkboxes under the 24px pointer-target floor. Each
waiver names one defect and matches only its own nodes, so the same rule still
fires anywhere else on the page.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Seven payload-bearing cassette entries answered success no matter what the app
sent: the four flow mutations, both create mutations, and the mkdir POST. Since
each assertion then reads canned cassette data, a wrong payload — a stale closure
deleting flow 6 while flow 5 is open, an unbound name field — repainted exactly
the asserted UI and the suite stayed green. Verified by flipping a pinned flow id
and a pinned path: both specs now fail on the unmatched request, and both passed
before.
Matching had to grow a level for this: `bodySubset` documented a deep subset but
compared nested values whole, so `{ input: { name } }` demanded the entire input.
It now recurses, which is also what makes the API-token pin possible — its `ttl`
is derived from the clock at submit time and drifts a second between runs, so
only the operator-entered name is pinned.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The listing is a `tree`, not a grid, so there is no columnheader for `aria-sort`
to live on — axe rates it a critical `aria-allowed-attr` violation on every
sortable column. The sort state is already announced through the button's label
("Sort by name (ascending)"), so removing the attribute loses nothing.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The probes carry `transition-colors`, so reading the computed background right
after hover() sampled a colour still interpolating away from the rest state —
the half of the gate that exists to catch hover regressions could not catch one.
Disabling the transition on the probes fixes it: verified by giving one variant a
deliberately unreadable hover fill, which the assertion now reports as "badge
blue on hover" and previously let through.
Key the probe list off the variant union so a new badge variant fails to compile
until it is probed, rather than silently going unmeasured.
Also correct two route-manifest ownerships that misdirect diff-scoping: the flows
provider is mounted by the detail route as well as the list, and the provider
detail page was attributed to the list route that never renders it.
Doc fixes: the route sweep is tagged @cross, not @coverage; the licenses link in
CONTRIBUTING resolved outside the repository; and the frontend prettierignore
duplicated entries prettier already reads from gitignore.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Four independent ways the signal misled:
Adding a label to a PR skips every gate job, yet the report still ran, found no
results file and overwrote a correct green comment with a red "no results". It
now returns early when the run carries no completed mock job.
A run aborted by the global timeout still uploads a results file whose failure
count is zero, so the header could go green over a red job; the verdict now
requires the mock job's own conclusion too.
The report's concurrency key was the branch name alone, so a fork PR opened from
a branch named `main` lost its comment to upstream `main` activity. The gate's
key split `opened` from `synchronize`, leaving both runs live so the older one
could finish last.
Stand failure screenshots carried the stand URL and the login into a public
artifact — screenshots are now tier-aware like traces and videos already were.
Also guard the Tier-2 teardown: the trap is the script's last statement, so a
teardown hiccup turned a passing run red.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The "Success" badge and the all-passed accordion badge were assembled from raw
utility classes (`text-green-600` on a green tint, no dark override) instead of
the shared variant, so they kept the pre-unification shade and render at about
3:1 in light theme — under the 4.5:1 floor every other colored badge now meets.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The sticky PR comment took its header from the whole-workflow conclusion, so a
visual-snapshot diff — advisory, never a required check — rendered a red ❌ over a
"62 passed, 0 failed" mock-tier stats line, reading as a gate failure it isn't.
Track the header on the mock gate instead (✅ pass / ❌ real failure) and surface a
differing visual job as a separate ⚠️ line pointing at the diff artifact.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A used template variable read as green in the Available-variables panel (its
"used" badge) but violet in the editor highlight — the same entity, two colours.
Swap the editor variable to green and the <xml-tag> highlight to violet so it
stays distinct. A pure hue swap: lightness and chroma are untouched, and every
token still clears WCAG AA in both themes (tightest is the dark tag at 5.36).
Guard the editor palette in cross/contrast.spec.ts alongside the badges, mounting
the real .template-* rule so the shipped CSS is measured, not a copy — verified to
fail when a token is pushed under AA.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The last two uncovered detail tabs. Files turned out not to be REST-backed at all:
it runs its own flowFiles query, separate from FlowDocument, so it needed a keyed
cassette entry and paths under the manager's uploads/resources prefixes — a file
seeded outside those roots renders nowhere. Screenshots reads FlowDocument like the
other four; only its image is fetched over REST.
That image is the part worth guarding. It mounts behind an intersection observer
and loads lazily, so a spec that merely opens the tab never requests it — the first
version passed with the cassette entry removed. It now scrolls the card into view
and asserts the decoded width, since toBeVisible is satisfied by an element that
failed to decode. Removing the entry fails it twice over: zero width, and the
unmatched-call gate.
Serving those bytes needed the REST mock to stop assuming JSON, so entries can now
declare a content type and have their body passed through verbatim.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Nothing enforced the container requirement — only a comment mentioned it. Running
the visual project on a developer machine writes `*-visual-darwin.png` next to the
linux baselines: new files CI never reads, so it stays red while the repo collects
junk and nothing says why. Fail up front with the command to use instead.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Strict pixel comparison was stable across seven local container runs and failed on
the first CI run: /flows differed by 332 and 384 pixels, identically on both
attempts, so it is a systematic host difference in text rasterisation rather than
jitter. The pinned image fixes the renderer, not the machine under it.
A budget wide enough to absorb 400 pixels cannot notice the ~70 a palette change
moves, so this trade has no useful setting — pixels are the wrong instrument for
colour. Back to the default tolerance, with the reasoning recorded so the next
attempt starts from the CI measurement rather than a local one.
The masking-race fix from the same commit stays: it was a real defect.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The suite was carrying Playwright's 0.2 per-pixel default, a tolerance meant for
cross-machine rendering noise that the pinned container removes by construction.
It cost the gate its sensitivity: a real palette change passed while three
baselines silently went stale.
Compare strictly and bound the differing-pixel count instead. Measured over
repeated container runs, glyph antialiasing jitters by exactly 2 pixels, while the
palette change that slipped through moved 71 — so threshold 0 with a 20-pixel
allowance tolerates the noise and catches the class of change that got away.
Strict comparison also exposed a real defect the loose one hid: the flow detail's
ready locator was the header button, but the visual spec masks the terminal, which
mounts later. Capturing in that window compared live terminal pixels against a
masked baseline — a 261k-pixel diff, roughly a third of the frame, appearing at
random. The route now counts as rendered when its terminal exists.
Seven consecutive container runs are clean at the new settings.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Green sat a step darker than its siblings because green-700 measures 4.4991
against its tint — imperceptibly short of AA, but short. Carrying that as a
one-variant exception meant an odd shade number in the map, and the only ways to
let green back to 700 were to lower the gate for all eleven variants or to waive
it in the spec, which is the same exception wearing a different hat.
Move all seven to 800 instead. One rule, no exception, and the whole set clears
the bar with room: 6.39–7.83 on light, against 4.61–6.49 before — orange and
yellow had been sitting close enough that a later tint tweak would have pushed
them under. Dark is unchanged.
Three visual baselines were quietly stale: the earlier 600→700 move changed blue
text that the pixel comparison tolerated, since its YIQ metric under-weights a
blue-channel shift with little luminance change. Regenerated; two clean runs
confirm they are deterministic.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The palette fixes had no guard: no scanned page renders a colored badge or a
destructive fill, so a shade edit could silently drop a variant under AA and
nothing would fail. Two comments were standing in for that coverage.
Mount one probe per variant from the component's own cva — a class list copied
into the spec would only ever re-test itself — and measure what the browser
actually paints, so oklch tokens and translucent fills are read as rendered.
Every variant is checked at rest and on hover, in both themes.
The measurement is deliberately unrounded: green-700 comes out at 4.4991, which
two decimals report as a passing "4.5". With rounding in place the guard passed
against a deliberately regressed green; without it, it fails and names the
variant, the state and the ratio.
Specs can now import component modules, so the e2e tsconfig gains jsx.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Three comments added with the contrast fixes were mostly narration: two restated
the class strings they sat above, and two defended the implementation rather than
naming a contract. The one fact that is not visible from the code — green sits a
step darker than its siblings — belongs in a test that fails when it regresses,
not in prose asking the reader not to touch it.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Four states were under AA, not one: the dark badge and button at rest (3.71), the
light badge on hover (4.34) and the dark button on hover (4.40), plus the dark
destructive menu item (4.01). Badge and button had also drifted apart — one faded
to 80% on hover, the other to 90% — so each failed in a different theme.
The token itself cannot be retuned: sweeping its lightness finds no value that
serves both roles, because the same red is a fill under white text and the text
colour on the page. Darkening it for the fill would break the twenty-four
text-destructive call sites.
Tune the fill's opacity per theme instead, keeping white text and adding no tokens.
A translucent red composites toward what is behind it, so the same fade darkens it
on the dark ground and lightens it on the light one: full strength on light fading
to 90% on hover, 80% on dark dropping to 70%. Hover now raises contrast in both
themes. All four states land between 5.04 and 6.28, verified on a built bundle
against every dark surface token (worst case 5.13 on secondary).
The dark destructive menu item drops its focus wash from 20% to 10%, matching light
and restoring the label to 4.52 at the cost of a fainter highlight.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Every colored Badge variant carried a single text shade for both themes, and no
one shade clears WCAG AA on both grounds. Measured against the current tints,
five of the seven failed on light and four on dark, with red and pink failing on
both — the badge text is 12px semibold, so the bar is 4.5:1.
Use the darker shade on the light tint and the lighter one on dark:
text-{color}-700 with a dark:text-{color}-400 override. Green takes 800 instead
of 700 because a shade number is not a constant lightness across hues — green-700
measures 4.4991, just under the bar.
Every variant now lands between 4.6 and 9.7. The knowledges a11y waiver is gone
and both theme scans pass without it; the knowledges dark visual baseline is
regenerated for the lighter blue.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Measuring the variants (browser-resolved sRGB, the 10% tint composited over the
real card surface, WCAG formula) showed the defect is not dark-only: five of the
seven colored variants fail AA on light and four on dark, and no single text shade
clears both grounds. Blue happens to pass on light and fail on dark, which is why
only the dark scan flags it here. The waiver itself is unchanged.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Only the Terminal tab had a spec; Tasks, Agents, Searches and Vector Store — all
fed by the FlowDocument query — were uncovered. Add a populated flow cassette (one
entry per tab) and a spec that opens each tab and asserts its seeded content
renders. Files and Screenshots are REST-backed and left for a follow-up.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The route-manifest visual sweep only captured the empty providers state. Add a
populated cassette (enabled defaults + a user-defined provider row) and a dedicated
visual spec with light/dark baselines, generated in the pinned container. Dates
render deterministically because the visual project inherits the mock clock via the
backend fixture.
Also bind --update-snapshots=all in run-visual.sh so a trailing spec-file filter is
not swallowed as the option's optional [mode] argument.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The suite tags every spec but the docs only hinted at "@smoke, …". List the real
tags (@smoke/@flows/@crud/@coverage/@cross/@visual/@real/@stand) with their meaning
and how to filter, and spell out the two conventions the mock gate reserves:
@quarantine to isolate a flaky spec (excluded via --grep-invert) and @generated for
recorder-derived cassettes.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
axe only ran in the light theme, so dark-only contrast regressions were invisible.
Parametrize every a11y scan over light and dark. The dark pass surfaced a real,
pre-existing issue: colored Badge variants use text-{color}-600 with no dark
override and fail contrast on the dark background. Waive it narrowly on the
knowledges list (the blue badge) as named debt — a palette fix is queued
separately — so the rest of the dark surface is now gated.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The period-switch test only proved the usageStatsByPeriod refetch fired; it would
still pass if the UI rendered stale data. Key the cassette's usageStatsByPeriod by
period (week vs month) with distinct date ranges, and assert the Token Usage chart
x-axis shows the month range after the switch and drops the week range.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The comment claimed no non-backslash byte is lost, but GFM legitimately trims
cell-edge and collapsed whitespace, so the test asserts the weaker true invariant:
every byte other than backslashes and that trimmed whitespace survives in order.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The base compose file pins fixed network names, so any network left un-overridden
in this e2e override joins the stack to the developer's live observability and
langfuse networks. Give all three networks e2e-scoped names. Add a healthcheck to
the mock-LLM service and make pentagi depend on service_healthy, so a crash-looping
mock can never read as a started dependency and silently mask itself.
Update frontend/docs/e2e.md to match reality: the stand tier runs @stand only
(flow-run drives a real paid agent and stays local), every mock run rebuilds its
own bundle by design, and the trend/affected-routes notes.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The co-located components/shared/README.md documented hooks that no longer
exist. `usePagination` was never a hook, and the writer `useTableQueryFilter`
was replaced by the unified `useTableState`, so the copy-paste recipe it shipped
would not compile. Detail pages had likewise moved from spreading a `toolbarProps`
object to passing a `controller` prop.
Rewrite it as frontend/docs/list_detail_pages.md, matching the flat
per-subsystem layout backend/docs already uses: exact signatures for every
hook, component and storage helper, the wiring the five live list pages
actually use, and an explicit table of removed names so they are not
reintroduced. Drop the source-adjacent README — no other directory under
frontend/src or backend/pkg carries one.
Fix the comments that still named the removed hook, plus two claims in them
that contradict the code: the controlled filter is URL-backed only (DataTable
persists sorting, column visibility, page size and search columns, never the
filter), and `busy` on InlineEditInput disables the Save and Cancel buttons
while leaving the input editable.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The dashboard partial-errors spec matched cards via getByTestId('dashboard-card'),
but that attribute lives only in an uncommitted working-tree change, so on a clean
checkout the locator matched nothing and the spec failed. Match the data-slot="card"
attribute the shadcn Card primitive already emits. Also lift the inline xterm buffer
type in the message-rendering spec into named types so it satisfies prettier and the
union/module sort lint rules.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The smoke only exercised a successful login. Adds a cassette whose
/auth/login answers an error envelope and asserts the surfaced error plus
that Sign in stays disabled (react-hook-form holds it until a field
changes) — the negative path a live run confirmed but no spec covered.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The message cassettes were all Answer-typed, so flow-message.tsx's
type-specific branches never ran under test. A live QA run against a real
Bedrock flow showed real streams emit thoughts/report/terminal/input.
Adds a cassette with one message per path and asserts each: the
thinking toggle (thinking + message), a report that auto-expands its
details, a Terminal-format report that mounts the xterm renderer with
its output, and an input message's right alignment.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Real-tier (Tier 2/3) fixes, the blocking set:
- stand-smoke asserts a per-route anchor (breadcrumb title span) instead
of a shared sidebar link that 0-matches on /settings/* and double-matches
on /templates — the smoke was structurally red on 3 of 5 routes.
- stand-tier trace/video forced off (they embedded the session cookie and
the stand password in a public-repo artifact) and the stand project
selects @stand via config grep (the CI step selected zero tests).
- run-local-tier's sandbox filter is anchored to the seeded 9xxxx range
(`^/?pentagi-terminal-9[0-9]{4,}$`) so it can't force-remove a dev's
flow-9 sandbox; sandbox cleanup moved behind the keep-stack gate; compose
logs are captured before teardown.
- mock-LLM wraps the request handler (a non-JSON body crashed the process);
its transcript now issues a real terminal exec via a delegate chain and
flow-run asserts the terminal output; OpenAI-shaped error envelope.
Mock-gate rigor + coverage:
- order-insensitive deep-subset variable matching; unmatched WS subscribes
are now accounted at teardown; REST/GraphQL entries can pin a body/vars
subset; favorite-star asserts the persisted (not optimistic) value.
- new flows/create smoke (the primary journey had no mock coverage), a
graphql-ws protocol unit test against the real client, and a
route-manifest completeness test.
- affected-routes no longer under-scopes shared component dirs.
Hygiene: .mjs tools now linted/prettier'd; dead gitignore line; JSDoc/
sheet aria-label/schema-compat/trend/serve-dist/report-comment fixes.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
new RegExp(route.replace(/\//g,'\\/')) tripped CodeQL
js/incomplete-sanitization (only slashes escaped). The routes are
constants, so it was a false positive — but the predicate form is
cleaner and asserts the exact pathname.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
schema-compat set NODE_TLS_REJECT_UNAUTHORIZED=0 process-wide (CodeQL
js/disabling-certificate-validation, high). A real stand has a valid
cert; only the local self-signed Tier-2 stack needs it, so the operator
now opts in via their own shell env, never in code.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Lays the Phase-3 substrate on top of the three tiers.
- schema-compat pre-flight (e2e/tools/schema-compat.mjs): introspects a
target backend's live GraphQL schema and validates every frontend
operation against it, so deploy skew (a renamed/removed field) fails
once, readably, instead of as dozens of red specs. Verified against the
live Tier-2 backend both ways: 105 operations pass, an injected bogus
field is caught with the exact location.
- trend aggregation (trend.mjs): turns a run's results.json into one JSONL
record (p50/p95 spec duration, slowest three, pass/flaky/fail) so slow
regressions are visible, not just green/red; CI appends it to a
90-day-retained artifact.
- diff-scoping (affected-routes.ts + affected.ts): maps a diff to the
manifest routes it touches via each route's owning sources — the
substrate for selective runs and for scoping the exploratory agent.
Pure mapping fn, unit-tested (backend-only → none; shared infra → all;
owned → that route).
- CI: an e2e-stand job (label-gated + a protected Environment whose
reviewers approve before secrets are exposed; schema-compat runs first),
a trend step, and an LLM-independent @stand smoke.
- docs: the stand tier, trend/affected tools, and the LLM advisory recipe
(playwright-mcp + init-agents + guardrails) — the recipe the
deterministic tiers plug into, not a bespoke bot.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
18 baselines (9 manifest routes × light/dark) compared only inside
mcr.microsoft.com/playwright:v<version>-noble, so pixels are identical on
every machine and CI; the wrapper derives the tag from the installed
@playwright/test version, making the pin drift-proof, and a CI guard
fails loudly if the workflow's container tag falls behind.
macOS hosts cannot run the visual project directly (parallel darwin
baselines) nor mount their node_modules into the container (native vite
binaries): the wrapper builds dist on the host and the container serves
it with a dependency-free static server — route mocks intercept API
calls before the network, so no proxy is needed. The xterm canvas is
masked (SwiftShader pixels are driver-dependent). Determinism proven by
back-to-back container runs. The e2e-visual CI job is advisory, never a
required check.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
specs/real/** now exercise the actual agent loop end to end: create flow
-> image/language/title -> tool-call-ID sampling -> subtask_list plan ->
done barrier -> subtask_patch refine -> report_result — with messages
streamed over the real GraphQL websocket and the flow settling in
Waiting. The mock LLM is ~150 lines of Node driven by a deterministic
first-match transcript; the custom provider env seam means zero backend
changes.
The stack is fully isolated from a developer machine:
- own compose project/network/ports (8444/5433), coexists with a dev stack
- --env-file /dev/null so the developer's .env (live keys, DOCKER_HOST,
config paths) never leaks into the e2e backend
- flow ids seeded from 90001: sandbox containers are named
pentagi-terminal-<flowId> on the shared docker daemon, so the range
keeps them clear of dev flows and makes runner cleanup unambiguous
(down -v cannot remove them — the backend spawns them outside compose)
- pentagi healthcheck via busybox wget (the alpine image has no curl),
since the base service has none and up --wait returns too early
Auth for live tiers moved to the canonical setup-project + storageState;
the localStorage seed is now mock-tier-only (a forged client session has
no cookie behind it and the first 401 wipes it). CI gains a nightly/
dispatch-only e2e-local job.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The suite's generative tests run with timeout 30000 — the new one missed
it and tripped vitest's 5s default on slower CI runners.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
setup-go's cache:true already caches the build and module caches keyed
on go.sum; the extra actions/cache step restored the same read-only
~/go/pkg/mod on top and failed with "Cannot open: File exists" whenever
both caches hit. Also sets the workflow's GITHUB_TOKEN to contents:read.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
marked's cell splitter honors \| only after an odd backslash run and
truncates rows that split into extra columns, so escaping the pipe alone
in text like a\|b produced \\| — a live delimiter that dropped the
trailing cells on the next load. An odd run + pipe has no exact GFM
encoding: the serializer now pads the run by one backslash, trading a
one-character gain inside the cell for structural integrity, byte-stable
from the first save. Covered by direct round-trips and a random \/|
payload property test.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Completes the scenario-catalog coverage on the mock tier (48 specs).
- dashboard: analytics/overview tabs (lazy mount), period switch verified
on the wire, and the per-card degradation path — a failed stats query
renders "Couldn't load" in its own card while neighbours stay live
(first use of error-response cassette entries)
- settings: prompts (the largest typed cassette — 15 agent + 12 tool
prompt configs), providers empty state, create form opens
- resources: REST-seeded file tree, and the mkdir journey proving the
full chain — REST mutation raises a world flag, the flag releases a
resourceAdded frame, the subscription cache merge grows the tree
- e2e/routes.ts: route manifest (paths imported from src/lib/routes so
a rename breaks compile) driving a data-driven NAV sweep over 9
routes; entries carry owning source dirs for future diff-scoping
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The token-reveal dialog (and any dialog with an explicit Close/Cancel)
exposed two controls named "Close" — ambiguous for screen readers and
for role-based locators in strict mode. The shared X is now "Dismiss
dialog".
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Builds on the mock gate: 26 new specs across flows, CRUD, and cross
concerns, all driven by typed cassettes against the production bundle.
- flows: no-duplicate and exact-set-disjoint message streaming across
concurrent flows (ID sets attached to the report), reconnect that
reconciles the missed delta exactly once, and the rename/finish/
favorite/delete lifecycle chained mutation->subscription-frame
- mock engine: streams move to one-driver-broadcast (flowUpdated is
opened by two providers at once; reconnect re-joins past the cursor,
delta-only) and frames can wait on world flags
- CRUD: templates, knowledges (required-validation proves no mutation
fired via the zero-unmatched teardown), api-tokens (inline create,
one-time secret reveal)
- cross: themes (seeded + toggled), responsive (Pixel 7 touch profile,
1279/1280 split boundary), a11y with a policy - critical/serious
floor plus a committed per-route allowlist
- terminal content is asserted through the xterm buffer (the WebGL
canvas has no DOM text): the hook now exposes the instance on its
host element
- app fixes surfaced by the sweep: the rows-per-page select had no
accessible name; the favorite star is useOptimistic and only
persists via the settingsUserUpdated frame - the spec now asserts
the real persistence path
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The default tier runs the production bundle (vite build + preview)
against a cassette-driven mock of the whole API surface — GraphQL over
HTTP, graphql-transport-ws subscriptions, and REST — so the suite needs
no backend, no keys, and no secrets, and fork PRs can run it.
- mock engine: (operationName, variables) matching with sequenced
entries and world flags (login flips /info guest->user without
call-order coupling); unmatched calls answer 501 and fail the test,
so nothing leaks through the vite preview proxy to a live backend
- ws mock follows the graphql-transport-ws contract the app's client
needs: immediate ack, nothing before ack, streams stay open, delta
cursors survive reconnects, drops use retryable close codes
- clock and timezone pinned on the mock tier: formatDate branches on
isToday/isThisYear, so unpinned cassette dates rot within a day
- cassettes are TS modules typed against the generated GraphQL types,
so schema/operation drift fails the existing tsc gate at compile time
- CI: fork-safe e2e.yml (read-only token, no secrets, no write steps)
plus e2e-report.yml posting a sticky PR comment via workflow_run,
resolving fork PRs by head SHA
- smoke specs (login redirect, form login, authenticated /flows render)
green on the mock tier; e2e/ wired into tsc, eslint, and prettier
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
List pages and the flow detail page no longer replace live data with a
full-page error on a failed background refetch — the error/redirect branches
now gate on the absence of data, not on the error alone. On a cold-cache load
failure the flow detail page renders an in-page ErrorState + Retry instead of
silently redirecting to the list, while a genuine not-found still redirects.
Retrying after a failed initial load shows the spinner rather than flashing
the empty state.
Reconnect reconcile: catch the aggregate refetch rejection (the per-query
wrapper doesn't cover it) so a transient failure during the sweep can't
surface as an unhandledrejection, and re-hydrate the REST-backed resources
slot — which the observable-query sweep skips — via a ws:reconnected event.
The flow provider gates its blocking spinner and subscription teardown to the
initial load only, so a background reconcile no longer overlays the page or
bounces the live subscriptions.
Terminal: clear() cancels any in-flight chunked write so its trailing chunks
can't land after the buffer was cleared; the search Clear (X) resets only the
query and keeps the task/subtask filter.
Smaller fixes: role="alert" on ErrorState, a keyboard-operable per-agent Test
control, the correct prompt-validation Alert variant, and dashboard error
props. Shared LoadingState and DashboardError components collapse duplicated
loading/error blocks; terminal write cancellation and the Apollo cache
policies both gain test coverage.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The GraphQL subscriptions are delta-only: the server registers a subscriber
for future events and never replays what it published while a client was
disconnected (and it drops events for a disconnected subscriber outright).
Nothing on the client refetched after the socket came back, so a websocket
drop during an active flow — a network blip, a laptop waking, a proxy timeout
— left a permanent hole in the streamed logs/messages/status until the user
manually reloaded the page.
Refetch the active queries on reconnect: graphql-ws hands `wasRetry` to the
`connected` handler, so on a retry (not the initial connect) call
`refetchObservableQueries()`, which re-runs the flow's queries and merges the
full current state back into the cache.
Verified live with a faithful drop (patched WebSocket, real `ws.close()` mid-
flow while the agent kept producing): before the fix the messages created
during the outage stayed missing after reconnect and only a reload recovered
them; with the fix they reappear automatically on reconnect, no reload. (A
CDP "offline" emulation does NOT reproduce this — it buffers the socket rather
than closing it, so use a real close when testing.) 1006 tests pass.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Round out the subscription coverage with createStreamingLink — the piece that
coalesces streamed assistant token updates. Export it (test-only) and drive it
with a controllable source plus a mocked clock.
Locks the three behaviors that make token streaming feel right: append parts
inside the 50ms throttle window are accumulated but not re-emitted (so the UI
isn't hammered), the next emission past the window carries the full running
message rather than the latest delta, and the final non-append part flushes the
accumulated total and clears the per-id cache so the same id can stream again.
Also confirms a non-assistant-log result passes straight through untouched.
1006 tests pass.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The link that folds live subscription events into the Apollo cache
(updateCacheForSubscription) had no coverage — MockedProvider replaces the
whole link chain, so it can't exercise this. Export it and drive it directly
against a real InMemoryCache configured like production (flow-scoped list
fields keyed by flowId).
Locks the routing rules: *Added appends + de-dups by id, *Created prepends
(newest first — not re-sorted by id), *Deleted removes by id, *Updated merges
an entity's fields in place without reordering (and appends if it's not yet
cached). Also covers the two subtle bits: flowId variant isolation (an event
for one flow leaves another flow's list untouched) and type-tolerant id
de-dup (a numeric subscription id matches a string id from REST hydration).
Also exports createSubscriptionCacheLink for future frame-level tests. Pure
additive exports, no runtime change; app verified still loading. 1003 tests pass.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The flow detail query runs with errorPolicy:'all', so a failed sibling field
(the flow's log lists are separate, nullable root query fields — terminalLogs,
messageLogs, etc.) surfaces an Apollo error while `flow` itself resolves fine.
Both the redirect effect and the provider's load-error toast keyed off "any
error present", so one flaky log resolver would kick the user back to /flows
and toast "Failed to load flow" over a flow that had actually loaded.
Gate both on the flow genuinely being absent (`!flowData?.flow`) instead of on
the presence of an error. A missing/invalid flow still redirects and toasts
(its non-null `flow` field propagates to a null result); a partial failure now
renders the flow and lets the affected panel show its own empty state.
Reachability confirmed from the schema (sibling log fields are `[X!]`, nullable;
`flow` is `Flow!`, non-null) — end-to-end confirmation folded into the P2-S5
live run. 996 tests pass.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The terminal wrote incrementally by diffing on array length alone: if the
new logs were at least as long as what had been written, it appended the
tail from the old length onward. That assumes the on-screen prefix never
changes — but the same component is fed filtered subsets, so narrowing a
search then clearing it grew the array back past the filtered length and
appended the full-log tail on top of the still-visible filtered lines,
producing a scrambled, partly-duplicated buffer.
Track the exact lines last rendered and only take the append fast-path when
they are a true prefix of the new array; otherwise clear and rewrite. Pure
streaming stays incremental (no clear); any non-prefix change rewrites.
Verified with a repro test (red before, green after): full -> filtered ->
cleared restores the full set, streaming appends never clear, and a
different filter rewrites. 996 tests pass.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Resetting a prompt to its default on the prompts list swallowed a failed
delete into console.error — sonner wasn't even imported — so the row stayed
Custom with no hint anything went wrong. Toast it, matching how every other
mutation in the app reports failure.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The flows list did what the other lists used to: on a failed load the provider
fired toast.error with no id — so each repeated failure while the backend was
down stacked another copy — and the page, never reading the error, fell through
to its "No flows" empty state, indistinguishable from an empty account.
The provider already exposed flowsError; read it on the page and render the
shared ErrorState with a Try again button (refetch, now also exposed), and drop
the toast effect entirely. Flows now matches templates/knowledges/resources.
Verified live: three failed refetches leave zero stacked toasts and one error
state with the button (previously three toasts + a false empty state); clicking
Try again after recovery restores the list. 993 tests pass.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The Empty error state named the failure but left the user stranded — the only
way back was a full browser reload. Give ErrorState an optional onRetry that
renders a "Try again" button, and wire every load-error site to re-run its own
query: templates, knowledges (the active list-or-search query), resources, the
three settings lists, and the two settings detail pages. The templates and
knowledges providers now expose refetch for it; the rest already had one.
Verified live: failing the templates query shows the error with the button,
and clicking it after the backend recovers clears the error and renders the
list — no page reload. 993 tests pass.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A failed delete/create/update on the provider and API-token lists parked a
persistent destructive Alert above the table, which lingered until the next
action and, for tokens, dumped the raw Postgres constraint text into a banner.
Every other mutation in the app reports failure with a toast; these two lists
were the exception.
Toast them too — the create/update handlers already swallowed the error into a
console.error, so this is the first real feedback they give — and drop the
banner, its error state (deleteErrorMessage plus the unread useMutation error
tuples), and now-unused ErrorAlert component.
Verified live: creating a token whose name already exists surfaces "Failed to
create token" as a toast (no second token written), with no standing banner
left behind. 993 tests pass.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A failed list query showed a one-line destructive Alert stranded at the top of
an otherwise-empty page — it read as leftover chrome rather than the page's
state. The detail pages and the route error boundary already render a failure
as a centered Empty: a large icon, a title, the message. The lists now match.
Add ErrorState (the shared Empty-error the detail pages were inlining) and use
it for the load errors on templates, knowledges, resources, and the three
settings lists, plus the two detail pages that had inlined the same markup —
eight call sites, one shape.
Resources previously only toasted its load failure from the provider while the
page kept showing "No resources yet"; it now shows the error state like the
others, and the provider drops the toast (and the now-unused sonner import).
The settings mutation-error banners stay on the inline Alert — those sit above
rendered content, where a full Empty would be wrong; they're a separate change.
Verified live: a failed templates query (GraphQL) and a failed resources fetch
(REST) both render the centered Empty error instead of a banner or a false
empty state; the healthy paths are unchanged. 993 tests pass.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The banner told the user "something failed" but left every card showing its
value — a down backend rendered Total Cost as $0 and each chart as "No data
for this period", numbers indistinguishable from a genuinely quiet account. And
when a single stat query failed while the other eleven succeeded, the banner
alarmed over an otherwise-healthy dashboard.
Give MetricCard and ChartCard an error state alongside their loading/empty ones
— a muted "—" / "Couldn't load", quiet rather than alarming — and wire each of
the dashboard's queries to its own card and table. A failed query now says so
in its own tile; the rest keep rendering their real data. The top-of-page
banner is gone.
Verified live: failing one period query leaves that chart as "Couldn't load"
while its neighbours draw real bars; a full stats outage fills every card and
table with the quiet error state and no lying zeros; the healthy path is
unchanged. 993 tests pass.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Five copies of the same destructive Alert — same variant, same AlertCircle,
same title-and-message shape — sat inline across the settings pages, and the
preceding load-error fix had just added four more call sites of it.
Use the shared component at all nine, and rename it to ErrorAlert on the way:
the name it shipped with an hour ago, DataLoadError, was too narrow for two of
the five, which report a failed delete rather than a failed load.
Its `message` now also accepts null, because that is what the delete-error call
sites already had in hand and what the inline JSX happily rendered as nothing.
Left as they are: the prompt-validation dialog swaps variant between success
and error and carries a structured body, and the flow-files notice is a default
Alert — a warning, not an error. Neither is this shape.
No behaviour change. Verified by re-failing the providers and prompts queries
and confirming the same alert still renders and the page still recovers;
993 tests pass.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A backend that was down rendered as a pristine empty account: every dashboard
chart said "No data for this period" and every metric card showed 0, while the
templates and knowledges lists showed their "nothing here yet" empty states —
all indistinguishable from a genuinely empty account, with no toast, no banner
and no other hint that anything had failed.
None of the three pages read `error` from their queries. The templates and
knowledges providers destructured only `{data, loading}` and never exposed it,
and every dashboard query dropped it on the floor. A failed query leaves `data`
undefined, which the empty-state branch cannot tell apart from an empty result.
Expose `error` from the two providers and render a load-error state distinct
from the empty state: a full-page alert on the lists, a banner above the cards
on both dashboard tabs. The settings pages already did exactly this, so the
shared `DataLoadError` gives those call sites one shape instead of four copies.
Templates also gained the loading state it never had — its empty state used to
show while the very first fetch was still in flight.
Verified by failing each query at the network layer and re-running the check
that caught it: templates and knowledges now surface "Error loading ..." rather
than their empty state, and the dashboard shows the banner on both tabs against
a cold cache. Happy path unchanged; 993 tests pass.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The proxy was only declared under `server`, so `vite preview` served the
production build with no route to the backend: every /api/v1 call 404'd and
the built app could not get past the login screen.
That left the production bundle effectively untestable, which is where
chunking — and the bug that made every route download recharts — only ever
shows up; `vite dev` does not chunk at all.
Reuse the dev proxy for preview, on VITE_PORT+100 so it cannot collide with
the dev server. Verified: preview serves on 8100 and /api/v1/info returns 200
through the proxy.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
`cmd/installer/wizard/logger` opens log.json from its init(), so importing the
package is enough to create one in the process's working directory. Running
`go test ./cmd/installer/...` therefore drops a log.json into every package
directory it runs from — four of them were sitting untracked in the tree,
one step away from an accidental `git add -A`.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Loading any page — /login included — fetched the `markdown` and `charts`
chunks, ~198KB gzip that the page never used.
Vite 8 bundles with rolldown, where `manualChunks` is a compatibility shim
over code-splitting groups, and a group captures its modules' dependencies
as well as the modules themselves. So `charts` (recharts) swallowed clsx and
`markdown` (react-markdown) swallowed react/jsx-runtime — both of which every
component needs, which dragged the two chunks into the entry graph and onto
index.html's modulepreload list. Returning 'react-vendor' from manualChunks
for those modules changed nothing: the group that captured them as
dependencies won regardless of the order the branches were written in.
Use rolldown's own `codeSplitting.groups` instead and rank the shared modules
above the heavy libraries that depend on them.
/settings/account now fetches 305KB of JS rather than 502KB; /dashboard 378KB
rather than 474KB, still loading `charts` because it draws charts. Verified
against the production build served locally: 10 routes render, console clean,
charts intact, 993 tests pass.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Empty declares `flex-1 … justify-center` (empty.tsx:9), but the list pages wrapped
it in a plain `flex flex-col`, so it collapsed to its natural height and hugged the
header while api-tokens — same primitive, same "nothing yet + CTA" shape — centred
in its `flex-1` wrapper. At 1920 the CTA jumped ~350px between the two pages.
The five wrappers on knowledges, templates and flows (loading + empty states) now
carry flex-1 like the eight that already did. SidebarInset is `min-h-svh flex-1
flex-col`, so the height is there to fill. Measured at 1920: knowledges and
templates now report the same 564 centre / 24px offset as api-tokens.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The size-4 sweep stripped four icons the sweep had no right to touch, and they
rendered at lucide's default 24px: the avatar's UserIcon and the theme
switcher's Monitor/Sun/Moon in the sidebar user menu.
The sweep assumed every listed container sizes its icons at any depth. Only
Button/Toggle/CommandItem do, via [&_svg]. SidebarMenuButton and DropdownMenuItem
use [&>svg], which reaches a DIRECT child only — and these four sit deeper, inside
an AvatarFallback and inside TabsTrigger, so nothing sized them.
Found by measuring rendered icon width across every route with the menus open,
not by re-reading the selectors: the avatar icon was the only one a closed-menu
pass could see. Verified after: no icon inside a button or menu row renders over
16px except EmptyMedia's, which is meant to be large.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The remaining 20 rendered Loader2 spinners carried a deliberate size or colour, so
the earlier pass left them. They convert cleanly after all: Loader2 is a lucide
alias of LoaderCircle (`LoaderCircle as Loader2` in lucide-react's d.ts) and that
is exactly what Spinner variant="circle" renders, while Circle merges an incoming
className over its built-in animate-spin. So each site keeps its size/colour class
and only drops the now-redundant animate-spin. Every rendered spinner in the app is
the Spinner primitive now.
flow-status-icon and flow-task-status-icon keep Loader2: there it is a value in a
Record<StatusType, { icon: LucideIcon }> map, not a rendered spinner, and Spinner
is a variant wrapper rather than a LucideIcon — it does not fit that slot.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Two mechanical cleanups over the same files.
<Loader2 className="size-4 animate-spin"> and <Loader2 className="animate-spin">
appeared 28 times across 20 files while Spinner variant="circle" — the same
LoaderCircleIcon with animate-spin already baked in — was the idiom elsewhere.
Loader2 spinners with a deliberate size (size-3/5/6/10/16) or a colour are left
alone: Spinner sets no size of its own and would fall back to lucide's 24px.
Separately, 51 icons carried className="size-4" inside a Button, DropdownMenuItem
or AppHeaderAction, all of which already force [&_svg]:size-4 on descendants, so
the class was a no-op. Only those 51 are stripped — the sites picked by walking
each icon's real JSX ancestors through the TypeScript AST, because an indentation
heuristic mistakes multi-line opening tags for the parent. The 40 icons with no
forcing ancestor (Alert, TabsTrigger, AppHeaderTitle, a resize handle) keep their
size-4: without it they would render at lucide's 24px.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The remove X was a raw button. It is a ghost Button now, sized to the chip's own
26px so the whole chip height is a hit target instead of the bare 14px glyph.
Negative margins keep the geometry identical: -my-[5px] and -ml-1 -mr-1.5 shrink
the margin box back to the 14px footprint the raw icon had, and [&_svg]:size-3.5
holds the X at 14px against Button's [&_svg]:size-4 descendant rule, which would
otherwise win on specificity. Measured against the old markup on the real
stylesheet: chip 26px and 107.3px wide, X 14px, X 21px from the chip's right edge
— all unchanged.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The Test affordance in each agent accordion header was a raw span reimplementing
outline-button chrome by hand (rounded border px-2 py-1 + hover:bg-accent + a
manual disabled style). It now composes Button asChild variant="outline" size="xs"
over that span, so it inherits the same outline chrome as every other action
button.
It stays a span, not a button: AccordionTrigger already renders a button and a
button-in-button is invalid HTML — verified live, zero nested buttons in the DOM.
The disabled styling stays hand-rolled because a span can't be :disabled, and the
onClick keeps its stopPropagation so clicking Test still doesn't toggle the row.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The four detail-page saves rendered two ways: knowledge as AppHeaderAction (a
primary CTA that collapses to an icon on mobile), the other three as a secondary
FormSubmitButton. FormSubmitButton buys nothing here — all three sit in the
header, outside the form's FormProvider, so its useFormContext read returns null
and they already submit via form= + a manual loading prop. Its real value is the
in-<Form> subscription, which its 8 dialog/auth consumers keep using untouched.
AppHeaderAction gains an optional loading (icon->spinner + disable); the three
header saves become AppHeaderAction like knowledge, so all four are now the same
primary CTA that collapses to an icon-only button (aria-label preserved) below
md. type="submit" is explicit because Button defaults type to "button". Verified
at 480px: label hidden, 32px icon button, aria-label "Create"; at 1440: primary
fill, label shown.
Researched the alternatives first: React 19 useFormStatus can't read a
form=-associated button (react.dev; facebook/react#27980) and targets native
form actions not RHF; and a Radix Slot asChild compose throws on FormSubmitButton's
two-child array and can't inject the spinner past child-wins prop merging.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Template title was the only single-line field with neither a FormLabel nor a
FormMessage, so "Title is required" could never surface and the field was
unlabeled while knowledge/provider label theirs. It now has both — verified live:
submitting empty shows "Title is required".
Also: descriptive placeholders on the template title and editor (matching the
sentence-style placeholders elsewhere), the Rename dropdown icon to size-4 (its
siblings are size-4), and the new-flow intro to the shared block (h2 + gap-2
instead of h1 + mt-2) so every create/edit intro is identical.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The provider Type combobox rendered as a Button outline — opaque bg-background,
a ChevronsUpDown icon and font-medium text — while every select on the knowledge
form is a transparent-bg SelectTrigger with a single ChevronDown. Side by side
the Type field read as a different control.
The combobox trigger now carries bg-transparent, px-3, font-normal and a
ChevronDown size-4, matching SelectTrigger; the model combobox's addon chevron
follows suit. Measured against the canon at 1440: transparent bg, chevron-down
16px opacity .5, h-9, px-3, weight 400 — identical.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The variables and presets popovers scrolled the page once their own scroll hit
the end — overscroll-behavior defaulted to auto and a non-modal popover doesn't
lock the body. overscroll-contain keeps the momentum inside. Reproduced at
375x640: wheeling past the popover's end moved the body 0 -> 204px; with contain
it stays at 0.
The prompt variables card now shows the variable count on desktop too, matching
the preset-count badge the template card already carries.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Below the split the presets card was a 599px block that sat under the fold, past
the editor — on the new-template form the editor is empty and the presets are how
you fill it, so the primary tool was hidden behind a scroll.
The panel now mirrors the prompt variables one: on desktop it stays the card in
the split; below 1280 its header becomes a full-width secondary trigger with the
preset count, opening a non-modal popover that holds the same preset list. The
list is shared by both wrappers; only the wrapper differs. In the stack the
trigger takes the presets' desktop slot — after the title, before the editor.
Applying a preset from the popover closes it (the popover is controlled), then
either fills the form or raises the existing replace-confirm dialog when the form
already has content — verified live at 390: fill, replace-confirm, and expanding a
preset preview inside the popover all work, and the desktop split is unchanged.
presetsList drops its useMemo to take an onApplied callback; typing does not
re-render the form (FormField isolates it), so the 11 collapsibles are not on the
keystroke path — confirmed by zero slow input events while typing on desktop with
all of them mounted.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Below the split, preventing the popover's open-autofocus left focus on the
trigger while the content sat in a body portal, so the first Tab landed in the
editor and the second dismissed the popover: the chips could not be reached by
keyboard at all. Before the popover existed they were inline tabbable badges, so
this was a WCAG 2.1.1 regression.
Both autofocus handlers are gone. They were written to protect the editor caret,
but ProseMirror keeps its selection across DOM blur, so they were never needed —
verified live at 390: opening now focuses the first chip, Escape returns focus to
the trigger, and clicking a variable still inserts at the caret the user left,
with the editor focused and the popover closed.
Also stop the shared chip cloud painting bg-background over the popover: dark
--background matches the page behind it, which flattened the popover to a
borderline. The two-tone well is the desktop card's business, so the fill moved
onto its wrapper, where it still contrasts bg-card.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
`pnpm run prettier` is a required CI step and it exits 1 on these five files at
HEAD while passing on them at 001c6c0, so the branch is currently red. Formatting
only — no logic touched.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The badge default height is 22px — text-xs' 16px line box, py-0.5 and a 1px
border — which crowds the 32px trigger. h-5 pins it to 20px; border-box leaves
18px of content for the 16px line box, so nothing clips.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The count badge sat on a bg-secondary button, where every neutral surface token
is within 1.08–1.23 contrast of it: secondary painted the pill invisible and
outline drew its border in --border, at 1.18. Only --primary separates (2.76), so
the badge is default.
The tab overrides exist because the desktop panel sits on its own surface. Below
the split they fought the shadcn defaults, so they are xl:-scoped now — the same
1280 the layout branches on. Stacked widths get bg-muted with a bg-background
active tab again; 1280+ keeps bg-background with a bg-card active tab.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The trigger is a compact secondary button carrying just its label and, on the
right, the variable count — same count-badge shape the sheet and template
headers already use.
The badge is outline, not secondary: a secondary badge paints bg-secondary onto
a bg-secondary button, which renders the count as bare text.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The header and its hint were rendered twice below the split breakpoint: once as
the trigger label and again at the top of the popover it opened.
The header belongs to the wrapper, not to the shared part. On desktop it stays
the card header; on narrow widths it becomes the trigger, and the popover now
carries only the chips. Title and hint move to constants so the two wrappers
cannot drift apart.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Three follow-ups to the variables palette.
The chips composed badgeVariants onto a raw <button>, going around the primitive,
because Badge renders a div. Badge now accepts asChild through the same Slot
switch button.tsx already uses, so a chip is <Badge asChild><button>: the badge
keeps owning the styling, the button keeps native semantics, and the hand-rolled
role/tabIndex/Enter-Space handler stays gone. className has to stay on Badge —
Slot concatenates classes, so only cn() resolves font-normal against
badgeVariants' font-semibold.
Variables reads useBreakpoint itself rather than taking isDesktop from the page.
Every other consumer here does that, sidebar.tsx included, and it keeps the panel
droppable into the next page that needs one.
The narrow-width trigger is a full-width labelled button now. It carries no
chevron and no count badge: those, not the width, are what make a control read as
a value select.
Also size the popover by --radix-popover-trigger-width, the way autocomplete.tsx
does. It was 100vw wide and spilled across the sidebar between 768 and 1280.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
In the stacked layout the "Available variables" cloud sat between the tabs and
the editor, pushing ~530px of chips ahead of the content it annotates. The panel
now keeps its slot and its desktop rendering, and below the split breakpoint the
same cloud moves behind a { } trigger, leaving the editor at the top.
The cloud itself is shared by both wrappers; only the wrapper differs (card vs
non-modal popover). The popover must not trap focus: insert and cycle act on the
editor's stored selection, and cycling only helps if its highlight stays visible.
Chips are real buttons now — they were divs with role=button and a hand-rolled
Enter/Space handler that the native element provides for free.
Verified live at 500px: opening keeps the caret, clicking a used variable selects
the next occurrence in view, the popover closes as the editor takes focus back,
and the desktop split is unchanged.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
On narrow viewports the editor was rendered between the prompt meta/tabs
and the "Available variables" panel, splitting one logical block in two and
forcing a different composition per breakpoint. Merge them into a single
panel block that the desktop split and the mobile stack both render as a
unit, so the variables stay attached to the tabs they belong to.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Consolidate every empty / loading / error / not-found / error-boundary
state off the bespoke StatusCard onto the canonical shadcn Empty (already
used by DataTable) and delete components/ui/status-card.tsx. Empty renders
borderless and centered, so the wide-viewport "letterbox" look is fixed at
the root instead of capping a solid card.
Also in this pass:
- DataTable: truncate column headers so plain-string headers in narrow
fixed-size columns (e.g. "System Prompt") stop wrapping to two lines.
- Settings > Providers / API Tokens: move the Create action into the page
header (icon-collapses on mobile) and the API-token Playground/Swagger
links into a header overflow menu; drop the cramped description row that
needed the earlier truncate/flex-wrap workarounds. Those links use a
relative href since the API base path is root-relative.
- Settings > Prompts: drop the fixed size on the Name column of both tables
so it flexes to fill (matching Providers) and truncates.
- Settings > Account: keep "Member since" on one line at mobile widths
(min-w-0 + truncate, badge shrink-0).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Verified against the live /v2/search API: the response envelope only ever
populates data.web for this tool, and sources defaults to ["web"] when
omitted. The sources field carries a string-vs-object shape ambiguity across
the API/SDK/MCP layers (the Firecrawl MCP rejects string sources outright),
so dropping it removes a needless compatibility risk without changing
behaviour.
The down migration narrows the searchengine_type enum by casting the
engine column to a new enum that no longer contains 'firecrawl'. Any row
logged with 'firecrawl' would make that cast fail, so a rollback errors out
once the engine has been used. Remap those rows to 'tavily' before the cast
so the down migration is safe on real data.
The summarizer prompt asked the model to 'directly answer the user query'
but never rendered the query — Firecrawl's /v2/search response, unlike
Tavily's, doesn't echo the query back, so it was dropped when adapting the
prompt. Every summarized result (the common path, since scrapeOptions
requests markdown) was therefore a generic page summary instead of a
query-focused one.
Thread the query through search -> parseHTTPResponse -> buildFirecrawlResult
-> getSummarizePrompt and restore the USER QUERY line, matching Tavily.
Add a test asserting the query is present in the prompt.
- Summarizer prompt now uses one-based source IDs (aligned with the numbered
links) and the metadata-fallback title/URL, and truncates each document's
markdown to the same per-result limit as the non-summarized path, so an
oversized or hostile page can't blow up the prompt.
- Reword tool description, searcher prompt and docs to say 'main-content
markdown' since the scrape uses onlyMainContent=true.
- config.md example now uses the real NewFirecrawlTool(...) constructor,
matching the searxng/sploitus entries.
Add Firecrawl as a network search provider alongside Tavily, Perplexity,
Traversaal, SearXNG and the others. Firecrawl's /v2/search endpoint combines
web search with page scraping, returning full-page markdown content for each
result, which the searcher agent summarizes like the other content-rich
engines.
- New firecrawl tool mirrors the Tavily provider layer-for-layer: registry
definition, tool-type mapping, factory wiring in both tool builders, and
ftester executor/args/mocks support.
- Configurable endpoint: FIRECRAWL_API_KEY plus an optional FIRECRAWL_API_URL
(default https://api.firecrawl.dev) so self-hosted Firecrawl instances work.
- Adds 'firecrawl' to the searchengine_type enum (goose migration + models)
and the search-log server model so searches are recorded per engine.
- Installer wizard, .env.example, docker-compose, prompts and docs updated.
The tool is only registered when FIRECRAWL_API_KEY is set, so existing
deployments are unaffected.
Add an Off option to the per-agent Reasoning Mode control, gated on the model's
cannotDisable capability so it appears only where a disable actually takes effect;
relax the adaptive-only lock for disablable models; disable effort/max-tokens when
Off. Reconcile a stale Off when the selected model can't disable (e.g. after typing
a custom model name) so it cannot silently persist. Map the off mode through the
form->GraphQL conversion.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Add an explicit reasoning Off to the per-agent config, backed by the langchaingo
tri-state API. Off emits llms.WithReasoningDisabled() (the provider disable wire)
via BuildOptions, and UsesAdaptiveThinking is guarded so Off overrides the
adaptive-only auto-adaptive.
Per-model capability is derived at runtime from llms.ReasoningSupportFor and
surfaced through GraphQL ModelReasoningInfo, so the UI only offers Off where it
actually disables: cannotDisable reports when Off would be rejected (always-on
models) OR a silent no-op (an unclassified default-on model whose disable wire is
omitted), and capability is surfaced for any thinking-capable model (e.g. Gemini,
which declares thinking without a reasoning block). A new
ProviderType.ReasoningProvider() supplies the provider to the resolver.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- demuxExecStdout errors on a header cut short mid-frame (was a silent EOF that
dropped the tail) and surfaces a docker systemerr frame instead of discarding it.
- ftester drains telemetry on exit through the bounded observer.Drain instead of
two unbounded ForceFlush calls, so an unreachable collector can't hang it at exit.
- container-listing failures are sorted for a deterministic skipped-entries preview,
logged per-entry at Debug (the detail is already in the response and the endpoint
is hit on every navigation) with names quoted so control bytes in a hostile
filename can't inject into a log line; corrected the stat-failure comment
(a dangling symlink lstats fine, it doesn't fail).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The truncation slice and the demux stdout byte-cap had no docker-layer tests —
only the handler's Truncated wiring was exercised through the fake, so a
mis-slice or a dropped cap would have gone unnoticed. Extract find-output
parsing into a pure parseFindEntries and take the byte cap as a demuxExecStdout
parameter, then unit-test both boundaries (at cap / cap+1 / over-limit stream).
Also bound how many paths one container-files request may list
(maxContainerListPaths), so the per-path entry cap can't be multiplied by an
attacker-chosen path count into a large fan-out or response body.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The container-listing section still described the removed `ls -1` parse,
`pkg/queue`, and the old `[]container.PathStat` return. Update it to the current
`find -print0` + errgroup fan-out returning `ContainerDirListing{Files, Failures,
Truncated}`. Also remove the stale `WithBlock`/`DefaultDialTimeout` paragraph left
above the non-blocking `grpc.NewClient` test — its own next paragraph already
contradicted it.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Container-listing polish on top of the partial-success work:
- A directory whose entries all fail to stat no longer 500s. The find exec
already proved the container alive, so ListContainerDir returns the readable
entries (possibly none) plus the per-entry failures, and the handler serves a
200 partial listing; only a cancelled request or a dir that can't be listed at
all still errors.
- Over the entry cap, list the first page and set a Truncated flag rather than
erroring with end-user copy from the docker layer. The flag flows through to
the Pull dialog, which now warns the user the directory was truncated instead
of silently showing a subset.
- The Pull dialog no longer flashes a skeleton on an in-place refetch (Refresh,
or after a Pull): the listing hook clears its rows only when the path actually
changes, so a same-path reload keeps the current rows under the loading guard.
Tests: an all-entries-failed listing returns 200 with the failures; the
Truncated flag surfaces in the response. Swagger regenerated for the new field.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Three defects on the shutdown and container-listing paths:
- Telemetry drain ran the langfuse and otel sinks serially under one deadline.
langfuse's ForceFlush/Shutdown ignore the caller ctx and block on their own
timeout, so a langfuse outage burned the whole budget and the healthy otel
sink's final batch was never flushed. Add observer.Drain, which flushes then
shuts down each sink in its own goroutine bounded by the deadline; main uses
it, retiring the inline flush-then-shutdown dance.
- The partial-success listing put the raw stat/list error into the 200 body's
Failures[].Message, exposing docker-layer detail (container ids, the daemon
address) that response.Error only reveals under develop mode. Send a generic
message to the client and keep the raw text dev-gated, logged server-side.
- A path read successfully by one query could also appear in Failures when
another query failed on it, order-dependent. Reconcile at assembly: drop any
failure whose path was read successfully, so no path is in both arrays.
Also bound the exec stdout buffered before parsing so a compromised sandbox
can't stream unbounded output into memory.
Tests: Drain delivers a healthy otel sink while a langfuse sink blocks and
returns within its deadline; the listing failure message is dev-gated; a path
never lands in both Files and Failures. Live: unreachable collector -> shutdown
stays bounded (~5s) and exits cleanly.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The graceful-shutdown branch only logged "cleaning up resources" and exited
without flushing telemetry, so the last buffered batch was dropped on every
SIGTERM. Drain it, with three corrections:
- main: flush then shut down the observer on shutdown, bounded by a 5s
deadline in a goroutine so an unreachable collector can't stall exit.
Flush must precede Shutdown because the langfuse observer's Shutdown
cancels its context without flushing; its final batch drains only via
ForceFlush while the context is still live.
- observer Flush/Shutdown: drain both the langfuse and otel sinks and join
their errors instead of returning after the first, which skipped the
second sink entirely when both were configured.
- telemetryClient Flush/Shutdown: attempt all three providers and always
close the grpc connection, joining errors, so a stalled provider flush
no longer skips the rest or leaks the connection.
Tests: the langfuse observer test proves Shutdown drops the buffered batch
while ForceFlush drains it to the sink; observer-level tests prove both
sinks drain and errors aggregate. Live: with an unreachable collector,
shutdown stays bounded (~5s) and exits cleanly instead of stalling ~10s.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The startup dial used grpc.WithBlock with a 10s timeout, so a set-but-
unreachable collector stalled main() for up to 10s, and once that dial failed
the client was nil forever — a collector that came up later never connected
without a restart. Switch to grpc.NewClient (non-blocking): startup never
stalls and gRPC re-establishes the connection in the background on its own.
Also build all three exporters before any provider, so the exporter-error
cleanup (closing the connection) happens before any batch/reader goroutine
starts and can't leak one. Drops the deprecated WithBlock/WithReturnConnectionError.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
ContainerFiles gained a Failures list when the container listing switched to
partial-success; regenerate the Swagger docs (swag v1.8.7, the pinned version)
so generated clients see the new field.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- Ignore the local `backend/vendor/` tree (187 MB, present only for the
vendored-fork build) so it can't be accidentally staged.
- Remove the architecture-table row for `pkg/queue/`, which was deleted when
the container stat fan-out moved to errgroup.
- Drop the internal "H4" report-id labels from the telemetry test — the
sentences already say what they guard.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
find -print0 already delimits with NUL, but the exec still ran under a TTY,
whose onlcr translation rewrites every \n in the stream to \r\n — including a
\n that is part of a filename — so a file literally named with a newline was
stat'd under the mangled name and reported unreadable. Run the exec without a
TTY and demux the resulting multiplexed stdout/stderr stream by hand (no new
dependency), so filename bytes reach the parser untouched.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Navigating to a new directory in the Pull dialog kept showing the old files
and old "N entries could not be read" banner until the response landed (the
hook never cleared its data at fetch start), and when every entry failed the
per-entry messages were shown nowhere. Clear files/failures when a fetch
starts, and render the first few failure messages in the all-unreadable
empty state.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The multi-path container listing still fail-fasted: a single bad top-level
path (nonexistent, not a directory, list failed) returned HTTP 500 and
blanked every path that had already listed. Record each such path as a
failure and keep going so the readable paths are still returned; only a
cancelled request aborts, and if every path fails at the directory level the
request is failed as a whole. Also drop a per-entry failure whose path was
already read successfully by an overlapping query.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Parsing `ls -1` output was unsafe: under the TTY the exec allocates, GNU
coreutils shell-quotes names — so a readable file with a space, quote or
non-ASCII byte was stat'd with the quotes and reported unreadable — and
busybox wraps every entry in ANSI colour codes, so on an alpine/busybox
image the whole listing came back unreadable. Switch to `find -maxdepth 1
-print0`: literal bytes, portable across GNU and busybox, and the NUL
delimiter survives filenames containing newlines. Cap the entry count so a
directory with hundreds of thousands of files can't fan out into that many
Docker API calls, and classify a cancelled request or an all-entries-failed
listing as a directory-level error instead of a misleading empty 200.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The container file endpoint now returns HTTP 200 with the readable entries
plus a Failures list when some entries can't be stat'd, instead of failing
the whole request. Plumb those failures through useFlowContainerFiles and
show a non-blocking warning banner above the readable files ("N entries
could not be read"), reserving the full error empty-state for a true
listing failure. When nothing is readable, the empty-state says so rather
than "Directory is empty".
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A single unreadable directory entry (dangling symlink, a file removed
between ls and stat, a transient /proc entry) used to fail the whole
listing with HTTP 500, blanking the file browser and discarding every
readable sibling. The frontend already expects /proc/sys to not fail
spuriously, but the backend did the opposite.
ListContainerDir now returns a ContainerDirListing{Files, Failures}: per-
entry stat errors no longer abort the batch. GetFlowContainerFiles serves
the readable entries as HTTP 200, carries the failures back in a new
ContainerFiles.Failures field, and logs each skipped entry (capped) plus a
degradation summary. Directory-level faults (not a dir, ls failed, container
gone) still return 500 — there is no partial to show. statContainerEntries
returns successes + failures instead of the lowest-index error.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The deleted queue normalized workers<=0 to a default; the errgroup helper
passed the count straight to SetLimit, where 0 deadlocks the first Go() on an
unbuffered semaphore and a negative value disables the bound entirely. The
sole caller hardcodes 20 so this was latent, but clamp it back so a future
config-driven count can't hang the listing or flood the Docker daemon.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
ListContainerDir was the only consumer of pkg/queue and discarded its ordered
delivery (the caller dedups and re-sorts). Replace the fan-out with a small
errgroup helper — SetLimit keeps the same 20-way bound on concurrent stats
against the Docker daemon, the caller's context propagates into each call,
results stay in input order, and the lowest-index failure is surfaced
deterministically — then delete pkg/queue. The helper was verified byte-
identical to the previous queue implementation across 600 randomized directory
shapes (sizes, failure positions, out-of-order completion) before removal.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Adds a fake OTLP collector so NewTelemetryClient can be exercised against a
reachable endpoint: it builds all three providers and both ForceFlush and
Shutdown export and tear down without error. Previously only the
not-configured and unreachable-dial paths were covered.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Adds scenarios for a non-positive worker count (must fall back to the
default, else nothing drains the queue and delivery hangs), a nil process
function (logs and drops each item without panicking), and a stable
instance id. Brings queue.go to full statement coverage and kills the
mutants that previously survived on the workers<=0 fallback.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Unit coverage for NewTelemetryClient: an unset OTEL_HOST yields ErrNotConfigured,
and an unreachable collector returns within the dial timeout instead of hanging
(a TCP-accepting, silent listener drives the WithBlock path).
Also close the grpc.ClientConn on the exporter-creation error paths — a
successful dial followed by a failed exporter New() previously leaked it.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The two-context design in ddd3916 was correct but fragile: the field named
`ctx` was the liveness signal goroutines must NOT bail on, while the real
cancellation signal was `stopCtx`. That inversion is the exact trap that
produced the earlier happy-path regression (bailing on `ctx`, which a normal
input-close cancels, dropped in-flight results). It also left a latent
restart-without-Stop hazard: a second Start() after input-close orphaned the old
stopCtx and shared wg, deadlocking a later Stop() (with a data race).
Collapse `ctx` into a plain `running` bool (it was only ever read via .Err(),
never awaited), keep `stopCtx` as the single cancellation signal, and guard
Start() on stopCtx so a restart requires a prior Stop() — removing both the
naming trap and the restart hazard.
Comprehensive tests (queue_scenarios_test.go): boundary-N full delivery,
contiguous-prefix-on-abandon, a randomized prefix-invariant fuzz, goroutine-leak,
restart-reject, process-error, double-stop, Running() transitions. The happy-path
tests hang on the pre-rework code and pass here (side-by-side under -race). Live:
a flow's non-empty container dirs of 1/40/100/500 files each deliver every entry;
the error path returns 500 without hanging.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The previous fix (97e5730) had workers and the reader bail on q.ctx, but the
reader also cancels q.ctx on a normal input-close — so the ListContainerDir
happy path regressed: after input closed (buffer names, close, read all N),
workers dropped still-undelivered results and the consumer hung waiting for the
last one. Any non-empty container directory that didn't error early hung the
file-manager request.
Split the signals: q.ctx still tracks "running" (cancelled by input-close or
Stop), and a new q.stopCtx is cancelled only by Stop(). Workers and the reader
bail on q.stopCtx, so a normal input-close drains and delivers every result
while a hard Stop() still unblocks a consumer that abandoned output. Stop()'s
already-stopped guard now checks q.stopCtx (input-close alone must not
short-circuit it, or blocked workers leak).
Tests: DeliversEveryResultAfterInputClose (hangs on the old fix, verified
side-by-side under -race) + StopHardStopsAfterInputClose; deadlock + ordering
still green under -race.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A set-but-unreachable OTEL collector hung startup: NewTelemetryClient dialed
with grpc.WithBlock() and no timeout on the deadline-free signal context, so
the process blocked forever before it ever served. And a non-ErrNotConfigured
init error from either observability client was log.Fatalf, killing the
process. Both let an OPTIONAL integration take the whole app down.
Bound the dial with a 10s timeout, and on init failure degrade to a no-op
observer with a logged warning instead of exiting. Verified live: a bad
OTEL_HOST that hung startup indefinitely now boots in ~14s with a warning and
runs a full flow; a reachable collector still boots in ~4s with no warning.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
ListContainerDir aborts on the first stat error and stops reading the queue's
output channel, leaving workers blocked on the unbuffered `q.output <- result`
send and the reader blocked on a full `q.queue`; Stop() -> wg.Wait() then hung
forever. Select every pipeline send/wait on q.ctx so a stopped queue unwinds.
On stop a worker returns without msg.cancel(), so later workers also bail via
q.ctx and output ends at a contiguous prefix instead of developing gaps.
Regression test drives the exact hang (unread output -> Stop must return),
verified with -race.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The openai-compat consolidation dropped the comment warning that DeepSeek needs
the legacy top-level "reasoning_effort" string form; without it a maintainer
could add openai.WithModernReasoningFormat() to the shared opts and silently
break DeepSeek thinking mode. Restore it at the shared opts choke point.
Also fix two stale pointers: glm/qwen config.yml cited
WithPreserveReasoningContent() "in glm.go/qwen.go", but it moved to
openaicompat.go during that same consolidation.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Export tokenNameSchema and pin the 100-character boundary (100 accepted, 101
rejected) plus its trim/default behavior.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- prompts_test.go: PatchPrompt rejects a syntax error, an undeclared variable,
and a whitespace-only template over REST (the path a raw client hits when the
UI is bypassed) and does not persist them; valid templates still create/update.
- validation_test.go: validateKnowledgeFieldLengths accepts each field at its
max length and rejects one character over.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The GraphQL createPrompt/updatePrompt mutations run validator.ValidatePrompt
(Go text/template parse + declared-variable check + trial render), but the
REST PUT /prompts/:type handler only checked the field was present, so a
prompt with a syntax error or an undeclared variable could be stored over
REST and later break rendering. Mirror the GraphQL check in PatchPrompt.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The create/edit form allowed 255 characters, but the backend caps token
names at 100 — a longer name cleared client validation and was rejected on
save. Lower the zod cap to 100 to match.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The REST handlers reject empty or oversized knowledge fields and over-long
API-token names through their request-model validate tags, but the GraphQL
mutations — the path the web UI uses — accepted them unchecked, so the same
entity could be stored past its documented limits depending on the caller.
Mirror the REST caps at the resolver boundary:
- createKnowledgeDocument / updateKnowledgeDocument: require content (and
question on create), and cap content/question/description/codeLang lengths.
- createAPIToken / updateAPIToken: cap the token-name length.
Limits are kept in sync with server/models via mirror comments.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The renameFlow / putUserInput / callAssistant GraphQL resolvers passed the
title/input straight to the controller with no non-empty check, while the
equivalent REST handlers reject them with 400. An empty flow title in
particular then fails the Flow model's `required` invariant and breaks the
REST GET /flows listing for that user. Mirror the REST guard at the resolver
boundary, matching the existing createFlow "... is required" checks.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The streaming ZIP refactor made `ZipResources` open each blob inline while
`streamZipArchive`'s writer commits HTTP 200 on the first byte. A blob missing
on disk (a DB record whose blob file is gone) failed mid-stream, so the client
received a 200 with a central-directory-valid but incomplete archive — the
missing files silently dropped (regression vs main, which buffered then sent).
Stat every blob up front; a missing one now returns before any byte is written,
so `streamZipArchive` emits a clean structured error instead. Keeps the
streaming memory benefit.
Tests (both proven fail-on-unfixed / pass-on-fixed): a unit test asserts the
writer stays empty when a blob is missing, and a download-handler test asserts
a missing blob in a multi-file ZIP returns a clean 500, not a truncated 200.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Drop comments that restate the code they sit on (public-route auth block,
app.tsx catch-all-route label, image-handle overlay description) per the
project's default-zero comment policy. Kept the load-bearing inline note that
password_change_required is local-users-only.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The multi-drag "N items" drag image set `hsl(var(--primary))`, but the theme
tokens are OKLCH values — `hsl(oklch(...))` is invalid CSS and dropped, leaving
a transparent badge with default text. Reference the tokens directly via
`var(--primary)` / `var(--primary-foreground)` (theme-aware, valid).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
`updateMessage` only mutated a ref, so the visible status ("Authentication in
progress...") never changed in production — it appeared to work only in dev via
StrictMode's double-mounted useLayoutEffect. Call setStatusMessage directly and
drop the dead ref + layout-effect machinery. The OAuth flow itself was already
correct (close/redirect use locals); only the visible text was frozen.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- main-sidebar.tsx: the three icon-only "New" quick-action links wrapped a bare
<Plus/> with no accessible name (WCAG 2.4.4/4.1.2) — add aria-label
"New flow"/"New template"/"New knowledge".
- editor toolbar heading/list/table-align menus: single-select options marked
the active one with only a visual <Check>. Add role="menuitemradio" +
aria-checked (mirroring the shipped Header-row menuitemcheckbox) so screen
readers announce which option is active. Visual affordance unchanged.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Both provider components built their context `value` as a fresh object literal
each render (providers-provider also re-sorted into a new array and recreated
its setter), forcing every consumer to re-render on each provider render.
Memoize the sorted array, the setter, and both value objects — the two
non-memoized outliers among the app's context providers. No behavior change.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Subscribing to `formState.isValid` via useFormState flips RHF's internal
`_proxyFormState.isValid`, which makes the zod resolver re-run over the WHOLE
form (13 agent accordions × ~19 fields + refines) on every keystroke — even
in onSubmit mode. `isValid` is only needed to gate the unsaved-changes dialog,
so validate lazily when that dialog opens instead of subscribing. Live INP on
the Name field: steady-state per-keystroke processing 152ms worst-case → ~5ms.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- vite.config.ts: drop the manualChunks 'monaco' branch — monaco was removed
in the monaco→tiptap migration (82b82c5), so the regex never matches.
- use-file-manager-selection.ts: remove `setSelection` — no caller destructures
it (file-manager.tsx never did); all writes go through rawSelectedPaths.
- settings-prompt.tsx: remove the unreachable `isNew` (promptId === 'new')
branch — nothing routes to /settings/prompts/new, and it would render a
"Create Prompt" header over a "Prompt not found" card. The real create path
is `isUpdate === false`.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The rich editor is a contenteditable div with role="textbox", which is
NOT a labelable element — a sibling `<FormLabel htmlFor>` can't name it,
and two of the three consumers (settings-prompt, template) render no
visible label at all, so the field had no accessible name (Lighthouse
A5). Thread `aria-label` through MarkdownEditorField to the contenteditable
(via the same view.dom passthrough as aria-describedby/aria-invalid) and
to the raw textarea, with each consumer supplying its name.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The inline "Create Token" row is a data row prepended at index 0, so an active
table filter (globalFilterFn) or a non-first page hid it — clicking Create Token
appeared to do nothing. handleCreateNew now calls setFilter(''), which clears the
filter and resets pageIndex to 0 (clearPageOnFilterChange default), so the create
row is always visible.
Live-verified (docker/HEAD backend): with a non-matching filter, Create Token now
shows the create row and clears the filter.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Follow-up to a55cac3 / 2a3a553. A percentage minSize scales with the screen:
30% is ~700px on a 2560px display and ~1000px on an ultra-wide — far too large
a floor. Give both resizable splits (DetailSplitLayout + flow.tsx) a fixed 390px
per-panel minimum (numeric = px in react-resizable-panels v4). defaultSize stays
a percentage: flow 50%, DetailSplitLayout 45%/55%.
Verified live (chrome-devtools, dev server, real flow + settings-prompt):
- 1280px (narrowest desktop): group 1024px, both mins 390px — no collision
(2x390 < 1024), drag range 390..633px.
- 2560px: min stays 390px (16.9%), not 691px (30%).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Same react-resizable-panels v4 pixels-not-percent pitfall as detail-split-layout
(a55cac3): flow.tsx's desktop two-panel split passed minSize={30}/defaultSize={50}
as numbers, so the 30 was a 30px floor — a user could drag either the central-tabs
panel or the detail panel down to a ~30px sliver instead of the intended 30%.
Use string percentages: minSize "30%", defaultSize "50%".
Verified live (chrome-devtools @1440px, dev server on a real flow): separator
aria-valuemin=30, dragging a panel to its minimum floors at 29.97% (355px).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
react-resizable-panels v4 reads numeric size props as PIXELS, not percent
("Numeric values are assumed to be pixels"). So `minSize={30}` was a 30px
floor — a user could drag either panel down to a ~30px sliver (~2.5% on a
1184px group) instead of the intended 30%. `defaultSize={45/55}` were px too
(they only rendered ~45/55% because default sizes normalize to a ratio;
minSize is an absolute per-panel constraint and is not normalized).
Use string percentages so the constraints mean what they read: minSize "30%",
defaultSize "45%"/"55%".
Verified live (chrome-devtools @1440px): separator aria-valuemin 2.536 -> 30;
dragging a panel to its minimum now floors at 29.97% (355px) instead of 30px.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Re-reviewed every frontend comment against the "names a concrete wrong action"
rubric. Cut pure restatements, change-narration, self-defense and bug-history;
trimmed mixed comments down to their load-bearing gotcha/contract; kept genuine
framework/API/security notes. Relocated a misplaced JSDoc in resources-provider
that sat on `error` but described `resources` (fields are alphabetically sorted).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The JS "desktop" threshold was 1200px, which is no Tailwind breakpoint, so anything
mixing useBreakpoint with a CSS `md:`/`xl:` variant for the same decision could drift
in the 1024–1279 zone. Move the threshold to Tailwind `xl` (1280) — mobile already
sat on `md` (768) — so JS layout switches and CSS variants now share the same values.
With the breakpoint a real token, MarkdownEditorField drops useBreakpoint and expresses
its height in plain CSS: fixed `h-[calc(100dvh-5rem)]` below xl (stacked forms, internal
scroll), `xl:min-h-0 xl:flex-1` to fill its pane on the desktop split. No JS hook, no
comment. Note: the split view now appears at ≥1280 instead of ≥1200.
Verified <xl live (fixed 1194px, internal scroll); the ≥1280 branch resolves to the same
`min-h-0 flex-1` fill already measured at 1440px — this browser window caps at ~1141px so
the wide layout could not be re-observed here.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The mobile/tablet branch used `min-h-[calc(100dvh-5rem)]`, only a floor — the
stacked forms have no flex parent to cap it, so a long document (a big agent
prompt is ~10k px of text) stretched the editor to its full content height and
the whole page grew with it. Make it a FIXED `h-[calc(100dvh-5rem)]` so the box
stays one viewport tall and the content scrolls inside it. Desktop (fills its
pane) is unchanged. Live-verified: the Adviser prompt editor is now 1194px with
an internal scrollbar instead of 10.6k px.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The mobile fixed height was knowledge-only; make it the field's job for all. The
field now derives its own height from useBreakpoint — the SAME hook the layouts
switch on — so it fills its flex parent on desktop and takes a near-viewport fixed
height on mobile/tablet, everywhere. Knowledge drops its last height className.
This also fixes the settings-prompt and template editors, which had no mobile
height and were cramped in their stacked mobile layouts. Live-verified all three
on desktop (fills) and mobile (min-h calc(100dvh-5rem)).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Every consumer embedded MarkdownEditorField in a `flex min-h-0 flex-col` column and
repeated `min-h-0 flex-1` to make it fill. Bake that default into the field (applied
first so a consumer can still override the height), and drop the boilerplate:
settings-prompt and template pass no className now, and the knowledge field only
keeps its one deviation — a fixed `min-h-[calc(100dvh-5rem)]` for the mobile stack
where it isn't inside a flex box. Live-verified all four surfaces: rich editor fills
(flex-1, min-h 0) on prompt/template/knowledge-desktop, and knowledge-mobile keeps
the fixed 100dvh-5rem height.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The prompt-validation dialog (max-w-2xl) and the provider-test-results dialog
(max-w-3xl) had the same latent bug as the Diff dialog: a bare max-w-* cannot
override DialogContent's default sm:max-w-lg at ≥sm, so both rendered at 512px
instead of 672/768px. Prefix with sm: so they reach their intended width.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The Diff dialog passed a bare `max-w-7xl`, but DialogContent's default already
sets `sm:max-w-lg`. tailwind-merge keeps both (different variants), and at ≥sm the
`sm:` rule wins the cascade — so the dialog was pinned at 512px and the split diff
overflowed with a horizontal scrollbar. Use `sm:max-w-7xl` so it overrides the
default at the same breakpoint, matching the app's other wide dialogs. Verified
live: the real Diff dialog now renders at 1280px with no horizontal scroll.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Renames the shared two-pane detail layout to DetailSplitLayout (file
detail-split-layout.tsx) and its slots left/right/rightClassName to
panel/content/contentClassName, which name the actual roles — a form/meta panel
beside the main editor content — instead of bare position. Updates all four
consumers (knowledge form, template, settings prompt, settings provider).
Also drops a dead GripVertical child passed to <ResizableHandle withHandle /> (the
handle renders its own grip and ignores children) and gives the left panel a
bg-card fill so the gutters around the centered card match the card colour.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Adds markdown-editor-heading-autoformat.test.ts (57 cases): levels, marker stripping,
negatives, hardBreak protection, every trigger path (delete/split/merge/insertText/
setContent/insertContent), the canReplaceWith container gate, multi-target ordering,
mark/variable/tag preservation, byte-fidelity interaction, and re-entrancy. The 6
ad-hoc Case B tests move here from the extensions suite.
Writing the coverage surfaced a soundness bug: promoting a MULTI-LINE paragraph whose
first line starts with `# ` (e.g. `# a`+Shift+Enter+`# b`, then deleting the lead-in)
emitted a heading containing a hardBreak, which re-parsed as TWO headings on the next
load. HeadingAutoformat now skips any paragraph that contains a hardBreak — a heading
is single-line — so such a block stays body text and escapeLineLeadingBlockMarkers
round-trips it. Single-line promotion is unchanged.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The heading input-rule fires only on the keystroke that types `# ` at a block
start. A block that comes to start with `# ` any other way — deleting the text
before an existing `#`, pressing Enter in front of it, pasting — stayed a
paragraph, diverging from CommonMark (a leading ATX marker IS a heading) and from
what the same text becomes on reload.
HeadingAutoformat, a ProseMirror appendTransaction plugin, promotes such a
paragraph to the matching heading (stripping the marker) on every doc-changing
transaction. It keys off the block's first child, not textContent, so a `# ` after
a hardBreak (Shift+Enter) correctly stays body text — that is a soft break inside
the paragraph, so the block does not start with `#`.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A paragraph line starting with "# " or "> " (reachable by Shift+Enter then such a
line — the heading input-rule only fires at a block start, not after a soft break)
serialized verbatim through the identity encoder and re-parsed as a heading /
blockquote on the next load, silently changing the block TYPE of body text.
Fix it as a symmetric pair: the paragraph serializer escapes a line-leading
`# `/`> ` to `\# `/`\> `, and the tuned marked Lexer's escape tokenizer — otherwise
off to keep `\d`/`\|`/`\\` literal — unescapes exactly `\#`/`\>` back on load. Only
these two markers are handled; `-`/`*`/`+`/`1.`/fences overlap with literal
regex/glob/backref escapes (`\*`, `\1`, `\|`) the editor must preserve, so they are
left alone. Real headings/blockquotes, regex/glob literals, and mid-line `#` are
unchanged (full byte-fidelity corpus stays green); adds pin tests.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The roving-tabindex MutationObserver watched childList:true/subtree:true, justified
by a comment claiming "the table control swaps button↔menu". Verified against the
source: the toolbar's item set is static (every control renders unconditionally;
state only drives pressed/disabled props), and each menu keeps its `data-toolbar-item`
trigger in the bar while swapping its content in a Radix body portal — outside the
observed subtree. So childList observed nothing. Keep only the load-bearing
attributeFilter:['disabled'] + subtree (a disabled toggle changes the roving set),
and correct the comment.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- history: assert resetUndoHistory actually empties the undo stack
(editor.can().undo() === false), not just that it doesn't throw — a silent
no-op regression would otherwise pass.
- field: assert insertAtCursor is a no-op (no onChange) when the field is
disabled — the documented "a mid-save variable click can't dirty the form"
guard was untested.
- content-integrity: the pipe-table generative test now also asserts each
pipe-bearing atom survives as an escaped code span, not just the row sentinels.
- code-fence: fix the pinned-limitation comment — an upstream fix turns this
test RED (the canary), it does not "flip green".
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The horizontal wheel-scroll handler treated the strip as "at end" only when
scrollLeft + clientWidth exactly reached scrollWidth. At fractional browser zoom
(125%/150%) those metrics never line up to the pixel, so the end was never
detected and the handler kept preventDefault-ing the wheel — locking page
scroll while the pointer was over the toolbar. Allow a 1px tolerance.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- index.ts: stop re-exporting findVariableUseRanges — every consumer imports it
from the module directly, so the barrel entry was dead.
- textarea.ts: drop Math.max(0, …) around textarea.selectionStart/End; both are
spec non-negative and non-nullable for a real HTMLTextAreaElement, so the guard
protected nothing. (The Math.max in the scrollTop math stays — it guards a real
negative subtraction.)
- link/image handles: rename the Popover onOpenChange param `next` → `isOpen`,
matching the boolean-naming convention and TableHandles.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Drop comments that restate adjacent code or defend a design choice, keeping only
the clauses that carry a non-derivable contract:
- useMarkdownEditor / useTableHandles: delete the responsibility-enumeration and
"rewriting only this hook" banners.
- clearLineContents: drop the "(Notion's Clear contents)" trivia, keep the
"structure intact, not a delete" distinction.
- normalizeImageSrc: keep the SVG-can-carry-script rationale, drop the restatement.
- nextVariableRange: keep the shared-by-both-panels invariant, drop the algorithm
walkthrough.
- image edit-form isEditing prop, two highlight-test negatives, and a table-pipes
test perf war-story: drop the restatements.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The link edit-form relied on a placeholder + aria-label with no visible <Label>,
and its invalid-URL alert had no aria-describedby back to the input — both
present on the sibling image edit-form. A screen-reader user who tabbed onto the
field after the error fired never heard why it was invalid. Add a visible Label
(via useId) and wire aria-describedby to the error id, matching ImageEditForm.
Also trim two comments per the zero-comment rule: the normalizeLinkUrl-return
restatement (documented at the callee) and the "(matches Docs/Notion)"
competitor-justification.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The three property-based tests each run 120–300 full editor round-trips and sit
right at vitest's default 5s limit, so they flaked to a timeout under a loaded
or serialized full-suite run (never in isolation, and never on an assertion).
Give them an explicit 30s budget so the full suite is deterministic.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
openRef was mirrored from the `open` state through a passive effect, but the
document-level mousemove handler and the stale-target droppers read
openRef.current on continuous events. Between a grip click (setOpen) and the
effect flush, a mousemove saw the stale null and retargeted the grip — and the
about-to-open menu — onto a neighbouring cell. Set the ref synchronously inside
onMenuChange before setOpen and drop the mirroring effect.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Unlike the link and image handles, TableHandles registered only scroll (and,
now, editor update) invalidation — never resize. Resizing the window reflowed
the table but left the fixed-position grips glued to their old coordinates,
detached from the table, until the next hover. Mirror the sibling handles and
drop the target on resize too.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The three overlay handles (link/image/table) each found their dismiss-on-scroll
parent with a hardcoded closest('.tiptap-content') ?? window, while the class
itself lived only inside markdown-editor.tsx's className string. A styling
refactor renaming that token would have silently sent all three to `window`
(whose scroll never fires for the inner overflow-auto), freezing popovers/grips
at stale coordinates — with no type error or failing test.
Export EDITOR_CONTENT_CLASS + getEditorScrollParent from the leaf styles module
and consume both from the className and the three handles. Behavior-neutral.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The link edit popover was keyed on `${range.from}-${range.to}`. Typing inside a
link grows range.to on every keystroke (the character inherits the link mark), so
<LinkEditForm key={key}> unmounted and remounted each keystroke and re-seeded its
URL field from initialUrl — silently discarding an in-progress URL edit and
churning the popover DOM.
Key on range.from alone: it is stable while the caret stays in the same link, and
still changes when the selection moves onto a different link.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
normalizeLinkUrl/normalizeImageSrc prepended https:// after stripping ALL
leading slashes (url.replace(/^\/+/, '')), so a root-relative path was
re-hosted onto its first segment: '/settings/profile' → 'https://settings/profile',
'/uploads/logo.png' → 'https://uploads/logo.png'. The result was non-null, so the
Apply button stayed enabled and the bogus href/src was persisted.
Extract toAbsoluteCandidate: only //host (protocol-relative) is promoted (prepend
the scheme); a single leading slash returns null (this field only accepts absolute
external URLs). Scheme-less hosts and existing protocol-relative cases are unchanged.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A hover grip captures its cell position once on mousemove and was never
invalidated when the document changed. Editing elsewhere (without moving the
mouse) then left cellPos pointing past the shifted doc, so two things could
happen: RowHeaderToggleItem's useEditorState selector called
hasHeaderRow(editor, cellPos) → doc.resolve(pos) → a synchronous RangeError
that takes down the whole editor render tree; and a "Delete row/column" ran
setTextSelection against the stale offset, editing the wrong line.
Guard doc.resolve in hasHeaderRow (an out-of-bounds position has no header
row), and extend the grip's existing scroll-invalidation to fire on editor
'update' too, so the target drops on any doc change and reappears on the next
hover. Adds the first unit tests for table-commands.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Pressing Enter in a table cell makes a second paragraph, and
renderTableToMarkdown joins a cell's block children with a raw U+001F
separator (outside renderChildren). That control byte was written verbatim
into the saved .tmpl/knowledge markdown and round-tripped back unchanged —
an invisible, persisted corruption of the file.
A GFM cell is single-line, so collapse the separator to a space on the
table's rendered output.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The line scanner only recognized top-level tables (^ {0,3}), so a `> `-prefixed
delimiter row failed TABLE_DELIMITER_LINE and the whole blockquote table went
unprotected — marked then stripped the prefix, parsed the table, and dropped
cells whose code span / template / URL held a pipe.
Detect a blockquote run, strip each line's prefix, recurse on the inner content
(reusing every rule here, so nested `> >` and fenced blocks inside the quote are
handled too), then re-apply the original prefix. Escaping never touches the
prefix, so untouched rows stay byte-exact.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
escapeRowPipes escaped pipes inside any `scheme://` run via a greedy
/[^\s]*:\/\/[^\s]*/g. Two bugs: (1) a long non-URL token (base64, a hash)
made that regex backtrack quadratically — 120k chars froze for ~11s on every
rich load, a stored, target-influenceable client-side DoS; (2) in a compact,
spaceless row like `|http://a.com|b|` the run swallowed the structural pipes
and escaped them, collapsing the row into one cell.
A URL pipe and a spaceless cell separator are indistinguishable in isolation,
so disambiguate by cell count: only escape scheme-run pipes when the row splits
into MORE cells than the header expects (a genuine phantom-cell URL pipe). A row
already at the right count keeps its structural pipes. The guard also skips the
scan on ordinary rows, and the replacement is a linear /\S+/g pass, so a long
token can no longer drive it superlinearly.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The escapeTablePipes fence tracker matched a fixed 3-char run (```/~~~) and
compared truncated tokens, so a 4-backtick block — which renderTunedCodeBlock
emits whenever the block's content holds a ``` line — was "closed" by that inner
3-backtick line. Two failures followed: pipes inside the real code block got
`\|` injected into the saved bytes, and a genuine table AFTER the block lost its
protection (the tracker thought it was still inside a fence), dropping cells.
Capture the full run and its trailing text; close only on a same-char run of
length >= the opener with no info string, mirroring CommonMark.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The pre-lex pipe protection split on '\n', leaving a trailing '\r' on every
line. The '$'-anchored TABLE_DELIMITER_LINE then failed to match '| --- |\r',
so the whole module no-op'd on CRLF input and marked dropped cells whose code
spans / templates / URLs held a pipe — silently losing data on the first load
of Windows- or API-authored content.
Normalize '\r\n' and lone '\r' to '\n' up front (marked re-normalizes the
returned string anyway). Original bytes are preserved when nothing is escaped.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The link cue in MARKDOWN_CUES was /\[.+\]\(.+\)/ — a double-`.+` that
catastrophically backtracks. isMarkdownLike runs synchronously in
handlePaste on every paste carrying an html flavor, so a large
bracket-heavy non-link paste froze the tab: 40k `[x]` reps → 3.7s,
120k → 33s (measured against the exact regex).
Bound both spans with negated classes (`[^\]]+`/`[^)]+`): linear-time,
matches real links identically (120k adversarial input drops to <1ms),
and now also catches multi-line link text. Add a ReDoS-budget regression
test and an invariant comment for future cue additions.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The built-in single deleteAction's JSDoc promised a "destructive variant"
but the object never set variant:'destructive', so the row-menu Delete
rendered as a default (non-red) item — unlike the bulk delete. Now that
the DropdownMenu/ContextMenu items support variant="destructive" and
file-manager-row forwards action.variant, set the flag so single deletes
read as destructive, matching the bulk action and the documented intent.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
FlowForm was the last form on raw useForm with mode:'onChange' (behind the
lint guard's inline disable). Migrating is behavior-neutral: the file has no
error UI, and RHF recomputes isValid eagerly on every change when it's
subscribed — so the send button keeps toggling live under useAppForm's
mode:'onSubmit' exactly as before, verified live (empty→disabled, typed→
enabled, cleared→disabled) across the composer.
Swaps useForm({mode,resolver}) for useAppForm({schema}) and drops the
eslint-disable. The !isValid submit gate and the three
setValue(...,{shouldValidate:true}) calls are load-bearing for the send
button (imperative setValue doesn't refresh isValid without the flag) and
are kept intentionally.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Two convention hardenings on top of useAppForm:
- noValidate on every react-hook-form <form>: validation runs through zod,
so native HTML5 constraint validation (type="email"/required) firing
browser-locale popups on submit is unwanted everywhere — not just the
email-change form that first hit it.
- no-restricted-syntax lint rule flagging mode/reValidateMode on useForm,
steering new forms to useAppForm (the single owner of the timing).
use-app-form.ts is exempted (it's the definition); flow-form keeps its
live-validation mode behind an inline disable pending its migration.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
LoginForm had no unit tests. Adds the convention-critical cases: fields
stay silent until the first submit (even after type+blur), submit surfaces
errors without calling login, fixing a field clears its error live once
submitted, and a valid submit calls login and navigates.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Our ui/* primitives were an older shadcn v4 generation. This ports the
low-risk, invisible/bugfix tier (Tier A of the drift audit), preserving all
local customizations (badge color variants, input spinner suppression,
textarea autoSize API, skeleton bg-primary/10, sidebar Cmd+B guard, etc.).
- data-slot="..." on ~33 primitives (was only 6); bare re-exports wrapped in
functions to host it. className strings verified identical to before.
- aria-invalid destructive styling on checkbox/button/toggle (was already on
input/textarea/select).
- resizable: replace dead data-[panel-group-direction=vertical] selectors with
the aria-[orientation=*] ones react-resizable-panels@4.11.2 actually emits
(latent — no vertical groups today; proven live via DOM experiment).
- dropdown-menu: viewport-aware max-h + overflow-y-auto on Content; add
variant="destructive" (mirrored on context-menu) and rewire file-manager-row
to use it instead of a hand-rolled className.
- checkbox: neutral border-input when unchecked, border-primary only when
checked (was always primary).
- input/textarea: min-w-0, disabled:pointer-events-none, dark:bg-input/30,
text-base md:text-sm (prevents iOS focus-zoom on mobile).
- sidebar: give the mobile Sheet real sr-only title/description.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
These primitives set aria-invalid (via FormControl) but never styled it, so an
invalid plain field showed a red label and message yet kept a neutral border —
while InputGroup/InputPassword and textarea-autosize already went red. Add the
same aria-invalid:border-destructive + ring the group primitives use, so every
field type reads the same when invalid (Input also fixes Autocomplete, which
wraps it).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The New Email field is type="email", so on submit the browser fired its own
locale-styled constraint-validation popup, pre-empting our zod error and looking
out of place. Add noValidate to the form so validation runs through zod/RHF and
surfaces the consistent in-app FormMessage ("Invalid email address") instead —
and it no longer masks the current-password error the native popup shadowed.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Move login, password-change, email-change, and name-change onto the shared
useAppForm wrapper — the last data-entry forms still on raw useForm. These were
already on react-hook-form's default timing (onSubmit + onChange revalidate), so
this is behavior-neutral: it only routes them through the single timing source
so none can later drift to eager validation, and keeps every form consistent.
Schemas and submit buttons (FormSubmitButton) are untouched, so the password
policy and login flow are unchanged.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Introduce a useAppForm wrapper that owns the validation timing (mode 'onSubmit'
+ reValidateMode 'onChange') and the zod resolver, so no form can drift back to
eager 'onTouched'/'onChange' that paints fields red before the user tries to
save. Three generics mirror useForm<Input, ctx, Output> for transform schemas.
Migrate every data-entry form to it (knowledge, templates, prompts, providers,
api-tokens, resources copy/move/mkdir, flow-files promote); submit buttons no
longer gate on isValid before the first submit (which would dead-lock a fresh
invalid form), except api-tokens which keeps its documented "disabled until a
date is set" gate. Full-height editor fields show the invalid state as a red
border (aria-invalid) with an sr-only message instead of layout-breaking text.
Also fills the knowledge editor to 100dvh-5rem on mobile.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Add feature-scoped --editor-* tokens (link/variable/tag/inline-code) instead of
reusing --primary, which is a fill color that fails WCAG AA as text on the dark
surface. Four distinct hues so adjacent tokens don't blur (blue link, violet
variable, teal tag, red inline code on a visible chip); every token clears
4.5:1 in both themes. Drop the Tailwind Typography literal `backticks` around
inline code, and mirror the editor's inline-code styling in the read-only .prose
viewer so a document reads the same whether it is edited or viewed.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Rework the editor toolbar into a shadcn-styled family of small modules:
heading and list dropdowns, an adaptive table menu (GFM-safe: no merge/split),
inline popovers for links and images with inline validation + URL normalization
(replacing window.prompt), click-to-edit link/image handles anchored to the
node, a reset-formatting action, roving-tabindex a11y, and tooltips. URL/image
sources are normalized to absolute https and gated by a protocol allowlist.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
NewBodyPair collects the indices of ToolCall parts with a nil
FunctionCall into partsToDelete, then deletes them in a forward loop
using those pre-collected ascending indices. Each deletion shifts every
later element left by one, so with two or more collected indices the
second and subsequent deletions remove the wrong elements: a valid
TextContent can be dropped while an invalid nil-FunctionCall tool call
survives into the message chain (feeding malformed messages downstream).
Iterate the collected indices in reverse so earlier indices stay valid
during deletion. Adds a regression test covering two leading
nil-FunctionCall tool calls followed by a text part.
- insertTextareaText → insertAtTextareaCaret: mirrors the handle method it backs
(insertAtCursor) and its sibling selectNextTextareaUse, and says WHERE it inserts
("textarea text" read as a noun phrase, not "text into a textarea").
- variableProbe → variableUseRegex: it returns a RegExp; the old name didn't signal
the return type (read as if it returned a boolean).
- dropUnderscore → dropUnderscoreRules: it filters input/paste RULES, not a character.
Behavior unchanged; 889 vitest green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
`cycleToVariable` read as "move to a variable" (a single target), but the method
advances the selection to the variable's NEXT use, wrapping — it cycles through the
variable's occurrences. `selectNextUse` says what it targets and matches the panel's
own "used ×N" terminology + findVariableUseRanges; it's the same family as code
editors' next-occurrence selection (CodeMirror's selectNextOccurrence, VS Code's
add-next-occurrence). The raw helper becomes selectNextTextareaUse. Behavior unchanged.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A comment audit against the zero-default policy: the module's comments are overwhelmingly
genuine framework gotchas (undo → silent data corruption / crash / perf regression) and stay.
Cut only the handful that fail the wrong-action test:
- the "closures read latest props" reassurance (no wrong action it prevents),
- two JSDoc lines that restated self-documenting function names (cycleTextareaToVariable,
insertTextareaText — the caret gotcha stays inline),
- two per-member handle JSDocs that restated method names (the interface-level mode contract stays),
- tightened the 6-line undo-clear block to 2.
No behavior change; 220 module tests green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
handleSetLink passed window.prompt output straight to setLink with no protocol check,
while the image toolbar already guards via isSafeImageSrc — so a user could toolbar-insert
`javascript:alert(1)` as a link href into the persisted document. Not a live XSS today (the
read-only viewer's react-markdown urlTransform and tiptap Link's isAllowedUri both sanitize
on render), but defense-in-depth: keep dangerous protocols out of the document at authoring
time so it never relies on every future render path sanitizing them.
Add isSafeUrl (mirror of isSafeImageSrc): allow http/https/mailto/tel + relative/anchor
(which resolve to the page protocol); reject javascript:/data:/vbscript:/file:/malformed.
Apply it in handleSetLink. Unit-tested alongside isSafeImageSrc; 889 vitest green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A full-feature review surfaced two real defects both living in the file that fixes
the table-pipe class — verified first-hand (repro + fix) through the real extension
stack and live on docker:
MEDIUM (data loss): escapeTablePipes escaped pipes only inside code spans and Go-template
actions, NOT inside link/image destinations or bare autolink URLs. A cell like
`[x](https://h/?a=1|2)` had its URL truncated at the pipe and the trailing cells silently
dropped on the FIRST load — the exact H1 corruption class, uncovered for URLs. Fix: a
URL_RUN pass escapes pipes inside any `scheme://` run (which never legitimately contains a
space, so a `|` in it is always content, never a real separator). Live: the URL and
trailing row now survive intact.
MEDIUM (ReDoS): TABLE_DELIMITER_LINE `/…\|? *:?-+:? *(?:…)*\|? *$/` had two adjacent ` *`
runs competing for the same characters, so a `|`-line followed by "dashes + a long space
run + a non-matching tail" backtracked O(n²) (2.4s at 64k) on every parse — mount, external
reset, paste. A crafted/AI-emitted doc froze the tab. Fix: a linear rewrite (trailing
`(?: *\|)? *$`, per-cell spacing) — same matches, sub-millisecond on the pathological input.
LOW: the imperative handle's insertAtCursor mutated a disabled editor (dispatch bypasses
the editable gate) and dirtied the form — guard rich on `editor.isEditable`, raw on `disabled`.
LOW (styleguide): `cs`→`computedStyle`, `looksLikeMarkdown`→`isMarkdownLike`, `endsTableBody`→`isTableBodyEnd`.
Tests: URL-pipe round-trip (link/image/bare, converges) + a real-separator-safety case +
a linear-regex ReDoS budget guard. 877 vitest green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Third-review MEDIUM-1: the field's imperative handle implemented cycleToVariable/
insertAtCursor only in rich mode, so settings-prompt reached around the component
with document.querySelector('#{formId} textarea') and hand-rolled a cycle algorithm
that was a structural duplicate of the rich one (drift hazard) plus formId plumbing,
a synthetic field object, a setTimeout caret restore, and a 35-line caretOffsetTop
mirror — ~80 lines of consumer bypass. This completes the already-shipped handle
contract (the same principle as making focus() work in both modes): the raw branch
now cycles/inserts over its textarea, both methods are required (drop the optional
`?`), and the cyclic "next occurrence" pick is one shared pure helper
(nextVariableRange) used by both surfaces. settings-prompt's handleVariableClick
collapses to mode-agnostic editorRef.current.cycleToVariable/insertAtCursor.
Also from the third review: LOW-1 the raw cn() argument order now puts the byte-exact
font-mono/no-resize classes last so a consumer className genuinely can't override them
(the comment claimed a contract the code didn't enforce); LOW-3 the handle contract is
JSDoc; LOW-5 the Suspense fallback forwards id/aria/disabled; LOW-6 the loading skeleton
and the editor's own placeholder share one wrapper class (extracted to a chunk-light
module) so first rich mount no longer flashes a different box; INFO-1 drop the unused
MarkdownEditorHandle barrel export; and a field-level unit test pins the mode-aware handle.
Live-verified on docker: raw + rich variable cycle work through the handle (querySelector
gone), console clean; 872 vitest green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Post-review fixes (CODE-REVIEW 2026-07-05_1048):
LOW-1 + LOW-2 (ref contract): the field's `ref` was typed `Ref<MarkdownEditorHandle>`
but only wired in rich mode, so RHF's focus-on-validation-error silently no-oped in
raw mode (a regression: the pre-extraction `<Textarea {...field}>` wired field.ref).
MarkdownEditorField now exposes one honest `MarkdownEditorFieldHandle` — `focus()` in
BOTH modes (raw textarea / rich editor), variable-panel methods optional (rich-only).
Consumers forward `field.ref`; settings-prompt composes it with its variable-panel
editorRef via a new `composeRefs` util. Added `focus()` to the rich editor handle.
Fixed Textarea's ref typing (was an accidental Ref<HTMLTextAreaElement> ∩ Ref<TextareaRef>
intersection; TextareaRef also now declares the focus() it exposes at runtime).
LOW-3 (fallback duplication): dropped the `fallback` prop — both consumers used it only
to swap the spinner glyph while hardcoding layout classes that had to track `className`
by hand. All three now use the default spinner, which threads `className` and carries
aria-busy for the lazy-load window.
Live-verified on docker: invalid submit focuses the field in raw AND rich; the prompt
variable panel still cycles/scrolls through the composed ref; console clean.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
MarkdownEditorField exposed three class props — className (rich wrapper),
contentClassName (rich content area), rawClassName (raw textarea). They are the
same concept: "size the field's outer box." The rich wrapper and the raw textarea
take identical flex/min-height layout, and contentClassName was used by exactly
one consumer for a mobile content floor that a wrapper min-height expresses just
as well.
Collapse to a single `className` applied to whichever element renders. Drop the
now-dead contentClassName prop from the underlying MarkdownEditor too. Consumers:
knowledge non-fillParent bumps min-h-[280px]→min-h-[320px] to keep the mobile
content area at ~240px once the toolbar wraps (previously floored via
contentClassName); template/prompt raw drop the min-h-[640px] floor and become
min-h-0 flex-1 like rich — flex-1 already fills at normal viewports (820px
measured), and raw now shrinks-and-scrolls consistently with rich on short ones.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The raw-textarea ⇄ rich-editor switch was hand-wired in all three consumers
(knowledge form, template page, settings-prompt), each repeating the byte-exact
raw config (autoSize={false} + resize-none font-mono) and its own lazy()/Suspense
boundary — and only template/prompt were lazy, knowledge pulled tiptap eagerly.
MarkdownEditorField centralises it: one owner of the mode switch, one place for
the raw="byte-exact source" contract, and one lazy() boundary so raw-only routes
never load the tiptap chunk. Because the field owns the boundary, the barrel can
re-export it eagerly (chunk-free until rich renders) and the a11y passthrough
now reaches the editor in template/prompt too.
Net -112 lines across consumers; settings-prompt's FormCodeItem + FormTextareaItem
collapse into one FormMarkdownItem (5 prop interfaces → 1).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The lead comment restated what the function name/body already say and
asserted a caller contract the single-arg function cannot enforce — that
"must not run on user edits" invariant is enforced and documented at the sole
call site (the value-sync effect's guard). Comment audit: everything else in
the module is current + earns its place.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The load-side escapeTablePipes was installed by patching MarkdownManager.parse
on the shared library CLASS PROTOTYPE — a process-global mutation that every
@tiptap/markdown consumer would inherit. Move it onto the module's own private
marked instance instead: subclass `tunedMarked.Lexer` so `lex()` runs
escapeTablePipes first. The manager builds its block lexer via
`new markedInstance.Lexer(...)` (including the construction-time initial parse),
so this is instance-scoped, catches every load, and touches no shared class.
`inlineTokens` is inherited unchanged, so inline fragments are unaffected.
Behaviour-identical (866/866 green, incl. the pipe-less table regressions);
drops patchManagerParse + the isManagerParsePatched guard + the MarkdownManager
import. Independent-review follow-up (CODE-REVIEW-markdown-editor-2026-07-04_1437).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The H1 table-pipe load fix (escapeTablePipes) only escaped body rows with a
leading `|` and stopped at the first row without one, and never escaped the
header. But GFM makes the outer pipe optional and marked treats a pipe-less
row as a table row, so a `|` inside a code span / Go action in a no-outer-pipe
table (`` A | B\n--- | ---\n`git log | head` | notes | done ``) was left
unescaped and marked dropped the trailing cell on first load — the exact H1
data loss, for the most common table style.
Widen the escaper to every row marked itself treats as the table: the header
plus all body rows up to a block boundary (blank line / heading / blockquote /
fence / list / hr / indented code — mirroring marked's gfmTable body-row
negative lookahead), never touching non-table lines (the escape tokenizer is
neutralised, so a stray `\|` outside a real table row would surface literally).
Regression tests for the pipe-less style + the block-boundary stop; the M7
generative oracle now emits both outer-pipe and pipe-less tables.
Found by an independent adversarial review (CODE-REVIEW-markdown-editor-2026-07-04_1437),
hand-reproduced via the round-trip harness before fixing.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
marked's GFM table tokenizer splits a row on raw `|` before inline
tokenization, so a pipe inside a code span (`` `x | y` ``) or a Go action
(`{{.X | upper}}`) in a body cell spawned a phantom column and silently
dropped the trailing cells on load. Pre-escape those pipes as `\|` before
the manager lexes (escapeTablePipes, scoped to real table body rows, fences
skipped); the splitter honors `\|` and restores the literal `|` in the cell.
Symmetric with TunedTable's existing save-side pipe escape, so it converges.
Patched on MarkdownManager.prototype because the Markdown extension parses
the initial content inside its own onBeforeCreate, before any lower-priority
extension can wrap the manager instance.
M7: extend the generative content-integrity oracle with a table-cell context
+ pipe-bearing atoms — the one class the single-context oracle can't produce.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
An inline-only rich paste (Google Docs/Word/mail single paragraph - <b>,
<a href>, styled spans) carries no block tags, so the paste plugin hijacked
it into a plain-text markdown parse and silently dropped bold/italic/links.
Defer to ProseMirror's native HTML parse when the clipboard has HTML and the
text/plain shows no markdown cues - the schema DOMParser keeps those marks.
Markdown-looking text (a VS Code copy of markdown source wrapped in
syntax-color spans) still parses as markdown, matching load.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A multi-encoded entity in prose (`&lt;`) intentionally loses one
encoding level per open+save cycle until fully decoded; inside code it is
byte-stable. Pinned so the cross-session behavior stays an explicit product
decision. Also correct the decode attribution in the tokenizer comment
(@tiptap/markdown's decodeHtmlEntities, not marked).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- M5: replace hand-rolled unknown-typed markdown types with the official
@tiptap/core exports (MarkdownToken/ParseHelpers/RendererHelpers) and
drop both casts they forced on the fidelity-critical paths
- M3: forward FormControl-injected id/aria-describedby/aria-invalid to the
ProseMirror contenteditable (field<->label association + error announce)
- M2: skip the redundant whole-document re-parse on mount (compare against
the captured initialContent instead of the normalized getMarkdown())
- L1+L10: extract the toolbar + isSafeImageSrc to markdown-editor-toolbar.tsx
and memo() it (parent re-renders per keystroke under RHF)
- L2: delete dead autoFocus/hasToolbar props (zero consumers)
- L3: drop dead match.index narrowing (required number under es2023 lib)
- L4: own vite chunk for marked; drop stale tiptap-markdown chunk pattern
- L8: TunedStarterKit / TunedTable (consistent Tuned* prefix)
- L9: shouldExternalSync -> isExternalChange
- L14: isSafeImageSrc data: allowlist narrowed to base64 raster formats
(data:image/svg+xml can carry script)
- L7: trim narration/restatement comments across module + tests
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- content: capture the initial value via useState so useEditor's
compareOptions no longer fires a redundant setOptions -> view.updateState
on every keystroke; the value-sync effect stays the single owner of
later content updates
- setEditable: guard on editor.isEditable to skip the redundant update +
getMarkdown() serialization emitted on mount
- drop the unreachable `if (!manager) return` in TunedMarkdownText -- the
Markdown extension always assigns editor.markdown; a non-optional cast now
fails loud on regression instead of silently reverting to the lossy encoder
- rename param h -> helpers in renderTunedCodeBlock (matches sibling helpers)
- trim the variable-highlight banner to the load-bearing node/mark invariant
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
"faithful" connoted a byte-faithful round-trip, but the editor now deliberately
normalizes some cases toward GFM (bare URLs autolink, named entities decode), so
the output is no longer byte-exact. "tuned" names what the code actually does —
tune marked's tokenizers + the code-block/table serializers for our content —
without claiming a fidelity property the output no longer guarantees. Pure
rename (createFaithfulMarked/FaithfulMarkdownText/parse+renderFaithfulCodeBlock/
StarterKitFaithful -> Tuned), no behavior change; 834 tests green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The `literalAmpersand` extension pre-encoded every `&` so @tiptap/markdown's
decodeHtmlEntities netted to a no-op, keeping `<`/`>`/`&`/`"`
byte-verbatim. But bare-prose entities in the knowledge corpus are HTML-encoding
artifacts from ingestion (e.g. `Time difference > 5 min` meaning `>`), and
freezing them as `>` is not what the author wrote. Drop the extension so
marked decodes the 4 named entities in prose (`<`->`<`, etc.).
Verified scoped and safe: numeric refs (`{`, `(`) and any entity inside
code / inline-code are NOT decoded (code content bypasses inline tokenizers), a
bare `&` survives as `&` (only valid entities decode), raw `<tags>` unaffected,
and the identity serializer keeps the decoded `<` from being re-encoded on save.
Full corpus (378 real knowledge docs): zero new non-convergence, zero
bare-&->& regressions. Live on :8000: `> 5 min` -> `> 5 min` on load+save
while numeric/code entities stay put.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The faithful marked layer neutralised marked's `autolink`/`url` tokenizers so a
bare `https://…`, `<url>` or email round-tripped as literal text. That was a
deliberate byte-fidelity choice, but the product decision is now to let URLs
become links. Drop the two tokenizer overrides and flip the tiptap Link config
to `autolink/linkOnPaste: true` so load, paste and typing all linkify alike
(the typing==load invariant is preserved).
Verified: removing the two lines has zero collateral — `<input>`, `__init__`,
`\d+`, `<` still round-trip byte-identical (handled by the other tokenizers),
and full-corpus convergence is unchanged (same 7/378 pre-existing non-convergent
docs with and without the change). URLs with `{PLACEHOLDER}` don't autolink;
URLs with balanced `$(…)` linkify and converge. Live on :8000: prose URLs render
clickable, code-block URLs stay literal, raw source stays byte-exact, load does
not dirty the form.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- Drop the insertAtCursor 'focus before scroll (same as cycleToVariable)' comment — the
gotcha is already documented at cycleToVariable's focus() 15 lines up; the parenthetical
was pure back-reference narration (report comment-audit).
- settings-prompt: document why one editorRef is shared by both prompt tabs (Radix unmounts
the inactive TabsContent, so only one editor mounts) and what would break it (F12).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
index.ts re-exported the heavy MarkdownEditor value, so any route statically importing
a light util from the barrel (settings-prompt / template import EditorViewModeToggle +
the variable probes) pulled the 527KB tiptap chunk into its eager graph — defeating
their lazy(() => import(MarkdownEditor)). Extract the pure {{ }} helpers (VARIABLE_RE,
variableProbe, findVariableUseRanges) into markdown-editor-variable-syntax.ts (no
tiptap), export only light utils + the erased Handle type from the barrel, and import
MarkdownEditor directly from its module (static in knowledge-form-controls, dynamic in
the two lazy routes). Verified at build-artifact level: settings-prompt/template chunks
now have ZERO static import of the tiptap/markdown-editor chunks — they reference the
editor only via import("./markdown-editor-…"). tsc + lint + build + 831 vitest green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
tiptap v3's useEditor does not re-render the component on every transaction, so the
toolbar's 16 editor.isActive()/can() reads went stale on selection-only cursor moves
— click into a bold word and the Bold button stayed unlit until the next doc edit.
Read all button states through a single useEditorState selector, which re-runs per
transaction and re-renders only when a state flips. Fixes the staleness and drops the
incidental full re-render. Idiomatic tiptap v3 pattern.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The handle test asserted only cycleToVariable's boolean return, so a regression to
'always select hits[0]' would stay green. jsdom has no layout, so the selection can't
be read directly — but insertAtCursor replaces the SELECTED range, making the target
observable: cycle twice, insert, and assert the SECOND occurrence (not the first) was
replaced. Distinguishes real advancement from a stuck-on-first regression.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- L2: the value-sync comment claimed setContent doesn't honor contentType — false for
@tiptap/markdown 3.27.1 (dist setContent parses via editor.markdown.parse). Collapse
the manual parse+setContent to setContent(value,{contentType:'markdown',emitUpdate:false});
verified byte-identical across 45 inputs (39 .tmpl + edge cases).
- L4: isSafeImageSrc comment overstated 'for saved content' — it guards only the toolbar
button; load/paste bypass it (inert; viewer sanitizes on render). Comment corrected.
- F9: the table pipe-escape comment implied the load path was handled — clarified it is
save-side only; a raw pipe in inline code on LOAD is a marked-tokenizer limitation.
- L5: hoisted the duplicated ~200-char wrapper className to WRAPPER_CLASS.
- L6: dropped the dead MarkdownEditorProps barrel export (+ its now-dead export keyword).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The round-trip tests asserted idempotence + word-multiset but not STRUCTURE, so a
word-preserving structural downgrade (a code block splitting, a dropped list item)
converged and passed green — the exact reason M1 shipped invisible. Add
structuralCounts() (structural node types, paragraph/text excluded as benign reflow)
and assert it in the corpus test (all 39 .tmpl) and a new generative nesting test that
composes primitives to depth ≥2 (ordered>bullet>code, blockquote>list, fence-in-fence)
— the historical drop class, now structure-preserving after the indented-fence + M1
fixes. Updates the stale 'ordered>bullet>code NOT generated' comment.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@tiptap/extension-code-block's renderMarkdown always emitted a 3-backtick fence, so
a code block whose content contains a ``` line (a doc demonstrating fenced markdown)
re-parsed as TWO blocks on the next load — the inner fence closed the outer. Override
renderMarkdown to widen the fence to longer than any backtick run inside (CommonMark).
Regression test: the nested-fence doc now stays one codeBlock and converges.
Also documents (with a pinned test) the sibling F2 case — a backtick INSIDE inline
code — as a genuine upstream limitation: @tiptap/markdown derives a mark's delimiter
from a fixed placeholder (getMarkOpening/getMarkClosing), so unlike a node it can't be
content-aware; the reviewer's suggested mark renderMarkdown override is a no-op
(verified against dist). Fixes the stale editor-markdown.ts pointer (L3).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
CI runs prettier --check over src/**; 10 files failed. The markdown-editor module
(7) + settings-prompt (1) drifted this session (eslint --fix was run without a
prettier pass after the rename/barrel + dep edits); knowledge-form-blocker.test /
knowledge-form.test (2) were pre-existing drift from an earlier commit. prettier
--write all; no logic change.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The 7-line jsdom polyfill (elementFromPoint + Range rects, needed for any editor
mount) was byte-identical across 7 test files, and the parse↔serialize roundTrip
harness re-declared in 3. Extract both into markdown-editor-test-setup.ts
(setupEditorJsdom + roundTrip); each test now imports them, killing the copy-paste
and the silent-drift risk if the required stubs change.
tsc + lint + full vitest (826) green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Component-level test (renders MarkdownEditor with a ref, reusing the jsdom
elementFromPoint/Range polyfills): cycleToVariable rejects a missing variable and
cycles/wraps an existing one without throwing; insertAtCursor emits the inserted
text through onChange; and the value-sync path suppresses onChange for an echoed
value while applying a real external change to the editor content. Exercises the
previously-buggy imperative-handle orchestration that composes the (individually
covered) findVariableOccurrences / resetUndoHistory pieces.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Export isSafeImageSrc (was module-private, so no test could reach the folder's only
security guard) and add an it.each unit test: allows http(s):// and data:image/*,
rejects javascript:, data:text/html, data:application/*, vbscript:, file:, and a
malformed URL (catch branch). Note: a bare relative string resolves to the page
origin and is intentionally allowed — the guard blocks dangerous protocols, not
non-absolute URLs (verified against the actual implementation, not assumed).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- FaithfulMarkdownText: drop the `export` — it has zero importers, used only
inline by createMarkdownLayer in the same file (its sibling createFaithfulMarked
is already a private const).
- markdown-editor.tsx: remove the reset-history tail comment that restated verbatim
the invariant already in resetUndoHistory's header (lines 52-53); the 'when it
fires' explanation above it stays.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The folder was the only shared/ folder mixing editor-* and markdown-editor-*
prefixes and lacking an index.ts barrel (all 6 siblings use the full folder-name
prefix + a barrel). Rename every non-entry module to markdown-editor-* (editor-markdown
-> markdown-editor-marked names its subject better), add an index.ts exporting the
public surface (MarkdownEditor + types, EditorViewMode/Toggle, the variable-highlight
probes), and migrate all 6 consumers off deep imports onto the barrel so future
renames stay internal.
tsc + lint + build + full vitest (813) green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The 8 flow-view search inputs used lodash/debounce via useMemo(()=>debounce(fn,500))
+ .cancel() cleanup. Swap to useDebouncedCallback(fn,500) from use-debounce — already
the repo idiom (data-table, input-search, use-table-state) with identical
leading:false/trailing:true semantics and the same .cancel() API. Drops lodash +
@types/lodash (a whole general-purpose lib kept for one function).
tsc + lint + build + full vitest (813) green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The 7 base UI components still on @radix-ui/react-icons now use lucide-react
(already the dominant icon lib, ~79 files). 1:1 name map: Cross2->X,
DragHandleDots2->GripVertical, Chevron{Down,Right,Up}, DotsHorizontal->MoreHorizontal,
MagnifyingGlass->Search, Check, DotFilled->Circle (kept a small filled dot for the
radio indicator via h-2 w-2 fill-current). One icon library instead of two.
tsc + lint + build + full vitest (813) green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- @tiptap/extension-{code,code-block,hard-break}: bundled transitively by
@tiptap/starter-kit, never imported directly in src — remove the redundant
top-level pins (functionality unchanged, editor tests 161/161 green).
- vaul + src/components/ui/drawer.tsx: dead shadcn wrapper with zero consumers.
tsc + lint + build + editor suite all green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@tiptap/extension-code-block's parseMarkdown gates on token.raw.startsWith('```'),
but CommonMark lets a fenced code block's opening fence be indented up to 3 spaces.
marked emits a valid code token whose raw then starts with that whitespace, so the
gate rejected it and the block was dropped on load. When a document mixed fence
indents the mis-detection cascaded and silently deleted everything after the first
dropped fence — a real knowledge doc lost 556 words (its entire second half) this way.
Override the codeBlock parseMarkdown to trim the leading indent before the gate;
otherwise identical to upstream. Also fixes the previously-pinned ordered>bullet>code
drop (same root cause) and recovers ~583 words across the 366-doc knowledge corpus.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
extensions was memoized on [placeholder], implying a live placeholder update,
but useEditor runs with empty deps and tiptap's setOptions merges options
without re-registering extensions — so a changed placeholder never reaches the
already-installed Placeholder plugin (verified: data-placeholder stays at the
mount value across a prop change). Drop placeholder from the deps to match the
autoFocus mount-only decision, removing the misleading reactivity signal and the
per-change rebuild of the whole extension array.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The generative oracle shipped green over the escape-tokenizer bug: its atoms
held only backslash-before-letter (which survives), and both oracles are too
weak for a first-load loss — survives/includes never ran on the missing class,
and convergence passes because the drop happens once then stabilizes. Add
backslash-before-punctuation atoms to the generative pool and a direct
byte-exact source-fidelity assertion for the escape class (regex/glob/UNC/
line-leading star), which is strictly stronger than survives+converges.
Fails on the pre-fix escape-active parser, passes on the neutralized one.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
createFaithfulMarked neutralized marked's del/emStrong/html/tag/autolink/url
tokenizers but left `escape` active, so marked dropped the backslash before any
CommonMark punctuation on the first load — corrupting regex `\.`, globs `\*`,
UNC paths `\\`, escaped `\[`/`\|` in real knowledge docs. A serialize-side
re-escape cannot recover a byte already gone from the doc model.
Neutralize `escape` too, so a source `\.` stays literal `\.`. With no escape
decoded on parse, the serialize side must emit text verbatim rather than
re-escaping (which would resurface as a literal backslash on the next load), so
encodeTextForMarkdown collapses to identity — load and save stay byte-symmetric.
Verified over the 405-sample corpus (39 templates + 366 knowledge): backslash-
punct loss 5 samples -> 0, byte-identical 104 -> 106, word-loss unchanged; 15
adversarial inline cases and table pipe cells round-trip clean.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Exports resetUndoHistory and drives it with a synthetic plugin that advances
view.state during the reconfiguring updateState — reproducing the exact
"Applying a mismatched transaction" RangeError in jsdom. Fails on the pre-fix
newState.tr, passes on the live-view.state.tr fix, so a future revert can't
silently reintroduce the production-only crash.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
resetUndoHistory dispatched newState.tr after view.updateState(newState).
updateState can synchronously advance view.state (a plugin view or tiptap's
deferred initial-content transaction firing during reconfigure), leaving the
stale tr's before-doc mismatched against the current doc — ProseMirror then
throws "Applying a mismatched transaction". This crashed the editor detail
page for ANY document containing a list, but only in the production build
(React StrictMode's dev double-mount masked the timing). Build the wake-up
transaction from the live view.state instead, whose before-doc is the current
doc by construction.
Live side-by-side verified on the docker prod build: the same list document
that hit the error boundary now renders; full torture doc keeps all atoms.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Add a seeded generative round-trip test (300 random docs combining every
content atom — dunders, {{.vars}}, <tags>, regex/path backslashes, HTML
entities, C++ — across paragraph/heading/list/quote/inline-code contexts):
asserts convergence and that no atom is dropped, catching combination-only
regressions the per-atom byte tests can't. Also correct the ordered>bullet>code
pinned-bug comment: marked keeps the code token; the drop is in
@tiptap/markdown's list reconstruction, not the marked parser.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@tiptap/markdown runs a module-scope decodeHtmlEntities on every text token
during parse, so a pentest doc that stores literal `<script>` (teaching
the encoded form) loaded as raw `<script>`, and `AT&T` as `AT&T`. Its
`.lexer()`/`.inlineTokens()` path never routes through marked's walkTokens or
hooks, so add a private-instance inline extension that emits each `&` as its
own text token pre-encoded to `&`; the decode then nets back to the
original byte, keeping the entity literal. Code tokens are untouched (decode
skips them) and literal `<tags>` still pass through unencoded.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Three StarterKit defaults corrupted content or diverged from the load path:
- Underline (`underline: false`): its `++text++` markdown tokenizer collapsed
the space in `C++ then C++` on load, and Ctrl+U emitted non-standard `++`.
No underline semantics in our content, so drop it outright.
- Bold/Italic underscore input+paste rules: typing `__init__`/`_word_` created
emphasis (`**init**`/`*word*`) while the same text loaded stays literal (the
marked layer neutralizes `_`), breaking identifiers on the typing path only
(input rules don't run on paste/load). Extend StarterKit to drop the
underscore rules (regex mentions `_`), keeping the `*`/`**` rules.
- Link autolink/linkOnPaste (`false`): a typed/pasted bare URL now stays
literal, matching load; explicit [text](url) and the toolbar still work.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
faithfulEscape backslash-escaped every `\`, so a save doubled regex classes
(\d -> \\d) and Windows paths (C:\Users -> C:\\Users) — 210/366 knowledge
docs carry such content. marked only treats `\` as an escape when it
precedes a CommonMark-escapable punctuation char; a `\` before a
letter/digit/space is literal. Escape a `\` only in that punctuation case,
leaving content backslashes verbatim.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Extract the paste decision into a pure `shouldParseMarkdownOnPaste` and
test all branches (plain text parses; empty, in-editor copy, block-tag
HTML, and code-context defer; styled-inline HTML still parses). Plus
integration over the real handler: pasted block markdown becomes rich
blocks, `_`/`__` stay literal like load, and rich block HTML defers to
ProseMirror.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The folder move nested the corpus test one level deeper, so its relative
walk to backend/pkg/templates/prompts needs one more `..`. The fix landed
in the working tree (tests were green locally) but missed the move commit's
staging, so HEAD carried the pre-move path.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@tiptap/markdown only parses markdown for initial content / insertContent,
never for the clipboard — so pasting block markdown (headings, lists,
tables, quotes, fences) landed as literal text while only StarterKit's
inline mark paste-rules fired, and `_`/`__` formatted on paste even though
load keeps them literal. Add a MarkdownPaste extension that routes
plain-text pastes through the same faithful markdown layer as load, so the
two are consistent. Rich sources keep ProseMirror's own fidelity: an
in-editor copy (data-pm-slice) and web/Office HTML (block tags) fall
through to the default path, and pastes inside code stay literal.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Move the 10 round-trip editor files (markdown-editor, its extensions, the
marked layer, inline-scan, tag/variable highlights, view-mode toggle, and
their tests) from components/shared/ into components/shared/markdown-editor/.
Consumers now import from the folder path; internal cross-references stay
relative. The read-only markdown viewer (markdown.tsx) stays put — it is a
react-markdown renderer, not part of the editor. Corpus test walks up one
more level to reach the backend prompt fixtures.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Tool prompts (and agents without a human template) rendered a lone
"System Prompt" tab, which looks unbalanced. Always render both tabs and
disable the Human tab when the prompt has no human template
(hasHumanPrompt = agent && hasHuman), so it greys out at 50% opacity
instead of vanishing.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Same light-mode collapse as the view toggle: an unconditional
bg-background track + bg-card active render as white-on-white in light
(background == card == popover), hiding the track. Scope both to dark
(dark:bg-background, dark:data-[state=active]:bg-card) so light falls back
to the default bg-muted track + bg-background active.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The dark-only restyle set an unconditional bg-background track + bg-card
active, which collapse to the same white in light mode (background ==
card == popover), so the segmented track vanished. Scope the raised
treatment to dark (dark:bg-background track, dark:data-[state=active]:bg-card)
and let light fall back to the default bg-muted track + bg-background
active. Same fix on the Theme picker. Also silence the hover/focus
highlight on the View row so it reads as a control host, not an action —
matching the Theme row.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Move the "View" row to the bottom of each actions dropdown — directly
above Delete when a Delete row exists, otherwise last. Swap the segment
icons to SquareMenu (rich editor) and Type (raw source), and give the
segmented control a dark-friendly treatment (bg-background track with a
bg-card active segment, matching the System/Human prompt tabs) so the
active segment reads as raised on dark. Apply the same treatment to the
Theme picker in the sidebar for consistency.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Replace the ad-hoc per-surface view-mode enums (`code`/`plain`,
`visual`/`plain`) and dropdown-item toggles with one shared
`EditorViewMode = 'raw' | 'rich'` type and an `EditorViewModeToggle`
segmented control (matching the Theme picker in main-sidebar). Applied
across all three editing surfaces: prompts, templates, and knowledge.
Rich is the default everywhere.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
marked's url/autolink tokenizers wrapped a bare https://…, <url> or email in
[text](text) on save — a content-changing rewrite of prompt/template/knowledge
prose. Neutralize both (same pattern as the html/tag/del/emphasis tokenizers);
explicit [link](url) and  still work via the untouched link
tokenizer. Pinned by byte-identity tests.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The Image toolbar passed window.prompt output straight to setImage; unlike the
link path, the Image extension does not validate the protocol, so a
javascript:/data:text/html src was stored. Not active XSS (the viewer strips it),
but a stored-content hygiene gap. Reject non-http(s)/non-image-data URLs before
setImage.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The corpus fidelity check compared word Sets, so a count drop / duplication /
reorder passed as long as each distinct word survived once. Assert the sorted
word multiset instead (the real guard the reviews flagged as degraded). Keep the
existing <=2-save convergence check — some templates canonicalize over two saves,
so save1 === save2 would be stricter than the codebase's contract.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The promptInfo-sync effect unconditionally reset BOTH the System and Human forms
on every promptInfo identity change, and neither useForm set keepDirtyValues. A
Save refetches settingsPrompts → promptInfo gets a new identity → the effect fires
→ the inactive tab's unsaved edits were silently wiped. This is the exact M3
data-loss class already fixed in template.tsx/knowledge-form.tsx, left unfixed in
this sibling. Add resetOptions.keepDirtyValues to both forms.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
marked's emphasis tokenizer fires on `_`, so `__init__`/`_word_` parsed to
strong/em marks and re-serialized as `**init**`/`*word*` — the underscores were
gone by serialize time (a serialize-side escape can't recover them). Two
external reviews reproduced this at DB level on real knowledge content. Neutralize
the `_` case of marked's emStrong tokenizer (defer `*`/`**` to the default, which
the toolbar emits) so Python dunders, snake_case and `_`-wrapped prose round-trip
verbatim; `*`/`**` emphasis is unaffected. Pinned by byte-identity tests.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Post-review comment hygiene: drop the editor-highlight-regex test header that
restated the describe/it names; drop the diffStyles "Tailwind vars" comment (the
satisfies type + name already convey it, and it mislabeled the one hard-coded
green); trim the knowledge-form performSave comment to its load-bearing half (the
backend trims/normalizes). The (M1) test-name tag was dropped with the
single-tilde test rename.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
marked's GFM del tokenizer accepts a single ~text~ as strikethrough, so prose
like "from ~5~ to ~10~" parsed into <del> and re-serialized as ~~5~~ —
corrupting ranges/paths in prompt/template/knowledge content. Neutralize the
single-tilde case in createFaithfulMarked (defer real ~~ to the default
tokenizer, drop a lone ~…~ to literal text), symmetric with the html/tag
neutralization already there. Double-tilde ~~strike~~ (the toolbar feature) is
unaffected.
Pinned by byte-identity tests for ~x~ pairs; the 366+39 corpus still converges.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The M3 unsaved-changes guard trapped the user after a successful CREATE: a new
template's form stays dirty (performSave reset only on the update branch) and
handleSubmit navigated to the list without telling the guard the navigation was
intentional, so useBlocker intercepted it and popped the "Unsaved changes"
dialog right after the template was saved. Move handleSubmit below the guard and
call guard.skipNextBlock() before navigate (mirroring knowledge-form).
Live-verified side-by-side: before — create stuck on /new with the dialog;
after — create lands on the list, no dialog.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Drop comments that restate the code or narrate a test assertion: the value-sync
intro (the skip-echo block below already explains it), the two PM descendants
return-value notes, the marked-cast type trivia, the 6-line aria-label essay,
the corpus-test harness/per-assertion narration (the it() title already lists
the checks), and two table/nesting assertion labels. Tightened the knowledge-form
"server's canonical document" note to its load-bearing line.
Kept the genuinely load-bearing ones the pass also flagged: the performSave
navigation/cycle warning (removing it invites reintroducing the guard cycle) and
the test "sanity" assertions (they prove the split/hard-break case is exercised).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The desktop two-panel resizable shell (outer flex, ResizablePanelGroup, left
45/30 panel + scroll + Card, GripVertical handle, right 55/30 panel) was
copy-pasted byte-identical across knowledge-form-layout, template,
settings-prompt and settings-provider. Extract a presentational
DetailTwoPanelLayout({left, right, rightClassName?}); the only per-page variance
is the right pane's inner className, exposed as an optional prop. Net -44 lines.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The Plain/Visual DropdownMenuItem sat inside the `canShowActions` (!isNew)
block, and the dropdown trigger itself was gated the same way, so a brand-new
knowledge doc was locked to the visual editor until first save — inconsistent
with templates, where the toggle is outside that gate. Move the toggle out of
`canShowActions` (Rename/Delete still require a saved doc) and show the trigger
whenever a toggle handler is supplied.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
diffStyles is a ~40-key constant (only literals + CSS var strings, no closure
over props/state) that sat in the component body. Lift it to module scope so it
is defined once, with a `satisfies` clause for the ReactDiffViewer styles type.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The page reset({text,title}) in an effect on every templateData change. Since
UpdateFlowTemplate returns the flowTemplateFragment, an inline title rename
normalizes the Apollo cache → the FlowTemplate query re-emits → the effect
refired → reset() clobbered the user's unsaved editor body. Switch to the
knowledge-form pattern: reactive `values` + resetOptions.keepDirtyValues, which
re-syncs server changes while preserving in-flight edits; delete the manual
reset-in-effect. Also add useUnsavedChangesGuard + UnsavedChangesDialog (the
page was the only detail page without navigate-away protection) and switch
mode onChange→onTouched (no full-schema zod on every editor keystroke).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
variableUseRegex built `{{[^{}]*?\.Name\b[^{}]*?}}` with two lazy spans; on an
unclosed `{{` with many `.Name` anchors it backtracked O(n²) (measured 25KB 49ms
/ 100KB 782ms / 250KB 4.9s — a multi-second main-thread freeze from one
variable-panel click). The panel COUNT path already extracted `{{…}}` blocks
linearly via VARIABLE_RE then probed each; apply the same block-first shape to
the two CYCLE consumers (findVariableOccurrences for the editor, the plain-mode
textarea cycle in settings-prompt) via shared findVariableUseRanges/variableProbe.
Same inputs now 0.16/0.21/0.48ms (~10000x at 250KB). Also escape the interpolated
variable name (a `.` in a name would otherwise match any char). Drop the dead
variableUseRegex; re-add InlineMatch.text so the doc scan can probe per block.
Pinned by a linear-time regression test on the pathological input + an escape
test; de-stales the editor-highlight-regex test header (scan is per-textblock
since 69f86ae, not per-text-node).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
faithfulEscape backslash-escaped every ~, but in GFM only ~~ is strikethrough —
a lone ~ is literal. Escaping it injected a stray \ into prompt prose (e.g.
~10%/~30% in generator.tmpl + refiner.tmpl), and since the editor's getMarkdown
output is the Go text/template stored and sent to the LLM, the \ shipped to the
model. Escape ~ only in runs of 2+ (a balanced ~~strike~~ is handled by the
Strike mark upstream and never reaches this path); backtick/backslash unchanged.
Pinned by byte-identity tests for lone tildes (the corpus test asserts only
word-multiset + convergence, so \~ slipped through).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Boolean presence flags use the has* prefix per the project naming convention.
showToolbar (MarkdownEditor) had no external callers; showLabel had one
(knowledge-form-layout) — renamed both together to stay consistent.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Review follow-ups:
- knowledge-form.tsx: drop the DirtyFlags comment (restates the type) and the
"backend also wipes subtypes" parenthetical (defends a redundant path).
- markdown-editor-extensions.test.ts: drop the roundTrip narration.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Review follow-ups on markdown-editor.tsx:
- drop onChangeRef/onBlurRef + their sync effect: tiptap invokes onBlur/onUpdate
via its own live options ref (`mostRecentOptions.current = options` every
render, @tiptap/react 3.27.1), so the closures already see the latest props —
call onChange/onBlur directly.
- memoize createMarkdownExtensions(placeholder) so it isn't rebuilt per render.
- trim three paragraph-length ref comments + the resetUndoHistory tail to their
load-bearing kernel.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
collectInlineMatches derived `to = from + match.length`, which undershoots
when a non-text inline node (a hard break from Shift+Enter) sits inside a
{{...}} or <tag> token: the highlight decoration and the cycle/select then
land one char short (off by the node's size). Read `to` from the per-character
position map instead. View-only — getMarkdown() was already byte-identical.
The module comment asserted the opposite (false) invariant; corrected. Test
inserts a hard break inside a token.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A {{.Var}} (or <tag>) split across text nodes by a mark — e.g. a user
styles one brace — was missed by the per-text-node scan: the cycle then
inserted a duplicate while the panel still counted it used, and the
highlight silently dropped on the fragment.
- new collectInlineMatches (editor-inline-scan.ts) scans each textblock's
concatenated inline text and maps offsets back to doc positions, so a
split token reunites in one block string.
- VariableHighlight, TagHighlight and findVariableOccurrences all use it.
- share one variableUseRegex + VARIABLE_RE between the editor and
settings-prompt (countVariableUses + the plain-mode cycle), replacing the
hand-synced duplicate regexes.
- test: a brace-styled {{.Foo}} is now found (was 0 before).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
insertAtCursor dispatched scrollIntoView before view.focus() — the reverse
of cycleToVariable — so the first post-load variable insert (fired from a
button outside the editor, before it is focused) would not scroll the
inserted text into view. Reorder to match cycleToVariable.
Also drop the unused getEditor() and focus() from MarkdownEditorHandle:
the only callers are cycleToVariable + insertAtCursor (verified by grep).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The "Available variables" panel could insert {{.X}} but, in the rich
(tiptap) editor, could not jump to an existing use the way the plain
textarea already did — the used-highlight + go-to-next were plain-only,
which read as a regression.
- cycleToVariable on MarkdownEditorHandle: finds {{.var}} occurrences in
the doc and selects + scrolls to the next one; returns false when there
are none so the caller inserts instead (cycle-or-insert contract).
- findVariableOccurrences (editor-variable-highlight.ts): the doc scan,
position-mapped to match the VariableHighlight decoration.
- panel isUsed = count > 0 in BOTH modes; handleVariableClick cycles when
the variable is used, inserts when not.
- focus before scrollIntoView: ProseMirror no-ops scrollToSelection on an
unfocused view, so the first post-load click would otherwise not scroll
(looked like a lost/double click).
- perf: the value-sync effect re-serialized the whole ~24KB doc twice per
keystroke only to no-op on self-echo; early-return when value is our own
last-emitted output (mount + real external form.reset still sync).
- tests: findVariableOccurrences span/word-boundary/unused cases.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@tiptap/markdown pins marked ^17 while our direct dep (report-pdf + the
editor's parser instance) is ^18, so two marked copies were installed and
the marked config needed an `as never` to bridge the version skew.
Add `overrides: { marked: ^18.0.5 }` so @tiptap/markdown resolves onto v18
too — one copy. Behaviourally a no-op for the editor (it already passed a
v18 Marked instance to the MarkdownManager; only @tiptap/markdown's unused
default + types change, and the lexer API is identical 17↔18). Narrow the
createMarkdownLayer cast from `as never` to a typed cast now that the
versions match.
Verified on the forced v18: tsc, 747 vitest, lint, production build green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Multi-dimension review found no bugs, leaks, or security issues; these are
the confirmed robustness + comment nits:
- resetUndoHistory: match the history plugin by PluginKey identity (a fresh
history() shares prosemirror-history's module-level singleton key) instead
of sniffing the undocumented stringified `history$` name — so an upstream
change fails loudly instead of silently turning the reset into a no-op.
- MarkdownTable: narrow `pipeEscaping as never` to
`as Parameters<typeof renderTableToMarkdown>[1]` so a future signature
change is caught at compile time rather than swallowed.
- Trim restating/duplicated comments in markdown-editor.tsx and
editor-markdown.ts; kept the genuine framework gotchas (reconfigure trap,
onBeforeCreate timing, setContent contentType, pipe re-parse).
tsc, lint, 747 vitest green; verified history() spec.key is a singleton.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Replace the unified rich editor's markdown engine: drop the community
tiptap-markdown (markdown-it parse + prosemirror-markdown serialize) and
our 5 prosemirror-internal monkey-patch extensions for the official
@tiptap/markdown (marked-based MarkdownManager). The consumer moves to the
new API (editor.getMarkdown() / contentType:'markdown' / markdown.parse).
editor-markdown.ts adds three small, supported-API customizations:
- a private HTML-neutralized marked instance so literal <xml-tags> survive
(marked otherwise swallows real-HTML-element names like <input>);
- FaithfulMarkdownText overrides MarkdownManager.encodeTextForMarkdown to
drop entity-encoding and over-escaping of literal punctuation;
- MarkdownTable wraps renderTableToMarkdown to escape cell pipes (#7884).
Verified: tsc, 747 vitest (rewritten extension + 39-prompt corpus tests),
lint, build; live on the dev stand — knowledge tables render and resize,
prompt <tags> stay literal (124 tag + 116 variable highlights, no
entity-encoding), console clean.
Known accepted bug, pinned by a test (marked parser, 0 corpus impact):
a code block nested ordered-list > bullet-sublist > code is dropped on
parse. Repro recorded for an upstream report.
Folds in the in-progress unified-editor work it depends on: knowledge
Plain/Visual toggle, settings-prompt and template editor wiring, the
CodeMirror removal, and the editor table/tag/variable styles.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
templates/{id} now mirrors knowledges/{id} and settings/prompts/{id}: a left
ResizablePanel (intro + title + the Presets panel, in the spot where the prompt
page shows "Available variables") and a right panel holding the Code/Plain
editor that fills the space. Save moves to the header (FormSubmitButton
form="template-form"); the right-side Presets sidebar/Sheet, the PanelRight
toggle, the in-input save button, and the Enter-to-submit handler are removed.
Live-verified on the stand: 2-panel render (create + edit), preset apply,
create->DB->reload byte-fidelity (incl. the blank line, reconstructed from
.cm-line), the Code editor filling the right panel, delete. tsc/eslint/build
+ 652 frontend tests green; console clean.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- providers: prove a stale user-provider row does not knock out a valid USER
sibling (TestGetProviders_StaleUserRowSpansValidSibling — ollama builds keyless
so it survives beside a skipped minimax; side-by-side verified).
- settings-provider: cover the create-form ?type=/?id= guards (disabled/unknown
type and clone-of-disabled bounce to the list; an enabled type renders). These
had zero coverage — a swap/drop-return regression would have shipped green.
- knowledge-form: cover performSave's server-document reset branch (untouched
fields reflect the returned document under keepDirtyValues), and the useBlocker
"Save and leave" path via a real data router (proceeds the blocked nav, does
NOT honor a CREATE redirect). Swap the negative no-navigate assertion's
setTimeout(0) flush for a deterministic Save-disabled anchor.
Each test mutation-verified to fail on the reverted production code; 652 frontend
tests + go test green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
From a strict re-review of the recent commits (no blocker/high/security found):
- providers.go GetProviders: the skip covers ANY unbuildable saved provider, not
only a disabled type — drop the misleading "of unavailable type" wording and
lower the line to Debug (it re-fires on every providers fetch; WithError keeps
the reason).
- settings-prompt countVariableUses: drop the redundant seed-in-map side effect;
the component already falls back to `?? 0` for unused variables, so the loop's
own `?? 0` is the only seed needed.
- settings-providers create menu: render a disabled "No available provider types"
placeholder instead of a silently-empty menu (loading / no-keys / failed-query
states), with a test covering it.
Counts live-verified unchanged (AgentType 1->3 on the stand); go test + 646
frontend tests green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Follow-up to b6d1036. Cloning an existing provider whose type is now disabled
(?id=) would have produced another dead provider — apply the same enabled-check
on the clone path. Adds a Vitest covering the create menu's enabled-only filter
(exports SettingsProvidersHeader for the render test; eslint sort-modules then
reorders it above the page component — declaration hoisting, no runtime change).
Live-verified: clone of the disabled minimax (?id=3) redirects to the list;
clone of bedrock (?id=2) still opens with a "(Copy)" name.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A user could create a provider of a type whose API key isn't configured: it
saved fine and showed in settings, but was dead for flow creation with no
signal (and used to break the whole providers query — see 08a24c9). Two layers:
- the "Create provider" menu now only offers types whose key is set
(settingsProviders.enabled, already fetched by the page), and
- the create form bounces a hand-typed ?type= that is unknown or disabled to
the list, closing the direct-URL bypass of the filtered menu.
Frontend-only. Live-verified on the docker stand: minimax/custom drop from the
menu (11 -> 9); ?type=minimax and ?type=garbage123 redirect; ?type=anthropic
still opens the form.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The knowledges feature had zero coverage while 01fa02d reworked its save/guard
logic. Add Vitest tests for the exported pure mappers (create/update inputs —
including the dirty-gated "" vs undefined distinction — and the zod
docType->subtype superRefine) and the component wiring (create -> navigate to
redirect, update -> no navigate, save-disabled-until-dirty, scoped
anonymize-disabled). The useBlocker dialog path stays covered by manual/live
testing (it needs a data router the component tests intentionally stub out).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A saved user provider whose type is no longer enabled (e.g. its API key was
removed) made GetProviders return an error for the ENTIRE `providers` query —
one stale row blocked all flow creation in the UI ("No available providers").
Skip and log such rows, mirroring how startup already tolerates disabled
default providers. Pre-existing robustness gap, not introduced by this branch.
Verified live on the docker stand: the `providers` query went from a hard
error to returning all 10 enabled providers (the stale minimax row skipped),
and flow creation works again. Adds a side-by-side regression test.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The "Available variables" badges recomputed a per-variable `.match` over
the whole template on every keystroke (O(variables × length)); fold them
into a single pass over the `{{ … }}` blocks. Tighten the action regex to
`[^{}]` so an unclosed `{{` cannot drive quadratic backtracking — closes
the self-DoS flagged by the security review.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Drop the function-behavior restatement; keep the actionable invariant (navigation
stays with the caller, else the guard↔onSaveFromDialog↔performSave cycle returns).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
From .cursor/rules/CODE-REVIEW-prompt-provider-commits.md (settings-prompt, code-editor):
- rename abbreviations currentIdx->currentIndex, pos->position
- drop the cycle-ternary restatement comment
- gate the green "go to occurrence" badge affordance to plain view (code view only inserts)
- move code-editor's byte-faithful note into an actionable JSDoc warning on the component
Cross-component uniformity: collapse the four scoped-useWatch wrappers (DiffContent,
VariablesPanelContainer, KnowledgeFormHeader, DeleteProviderDialog) to one consistent
"Don't hoist this useWatch..." warning, dropping the duplicated narration + provenance.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The provider `name` field was watched at the top of SettingsProvider but only
fed the delete dialog's itemName, so every keystroke re-rendered the whole form
tree (Accordion + 12 agent configs + resizable panels). Move the watch into a
small DeleteProviderDialog wrapper that subscribes on its own. Measured: typing
10 chars now re-renders SettingsProvider 2x (the one-time isDirty flip) instead
of once per keystroke; the per-keystroke re-renders land on the tiny dialog.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A Code/Plain toggle in the ⋯ menu swaps the autosize textarea for the
lazy-loaded CodeMirror CodeEditor, mirroring the prompt-template editor, so
flow templates with {{VAR}} placeholders edit byte-faithfully (no markdown
normalization). The toggle is available for new templates too; the editor
nests in the existing InputGroup shell so the in-input save button is shared
across both modes.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Typing in the knowledge markdown editor re-rendered the whole KnowledgeForm on
every keystroke: form.watch('content') — used only to toggle the anonymize
button's disabled state — subscribed the top-level component, dragging the form
body, layout, and metadata fields through a re-render per character. Measured on
a multi-KB document: max input processing 58ms -> 21ms, keystrokes over 25ms
20 -> 0, long tasks 1 -> 0.
- Move the content subscription into a small module-scope KnowledgeFormHeader
wrapper (scoped useWatch), so only the header reacts to typing; the form body,
layout, and editor stay put. Mirrors the existing pattern in
knowledge-form-controls.tsx.
- Removing the watch let the React Compiler optimize KnowledgeForm, which then
flagged the skipNextBlockRef latest-ref (react-hooks/immutability). Rather than
suppress it, untangle the performSave<->guard cycle the ref existed to break:
performSave now returns the result and the *caller* owns navigation. The form
Save button (defined after the guard) does the CREATE redirect via the stable
skipNextBlock; the unsaved-changes dialog's "Save and leave" saves and lets the
guard proceed the navigation the user initiated. No eslint-disable, no memo.
Behavior note: on CREATE, the Save button lands on the new document; the
"Save and leave" dialog now lands on the destination the user was navigating to
(it previously raced between the two). Verified live on the local stack:
create/update via button and dialog, delete on a dirty form, anonymize toggle.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
SettingsPrompt called form.watch('template') on both forms at the top level, which
subscribes the whole ~1000-line component to re-render on every keystroke (header,
tabs, panels, meta, all four dialogs). Move the live-template reads into small
useWatch children so only they re-render:
- VariablesPanelContainer wraps the variables panel (needs the live ×N counts).
- DiffContent wraps the diff viewer — live while the dialog is open, and Radix
unmounts it (and its subscription) when closed.
- handleValidate and the variable-insert callback read form.getValues() at call
time instead of the watched vars; the diff dialog's derived currentTemplate is
dropped.
Mirrors the existing knowledge-form-controls.tsx pattern. Verified with render-count
instrumentation that the parent no longer renders per keystroke (only the scoped
children do), and that the live count, variable insert/cycle, validate, diff (live
while open), reset, code-editor insert, and dual-tab dirty flows are unchanged.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Prompt templates are Go templates with markdown tables, <xml-tags>, and
significant whitespace — content a markdown (Tiptap) editor normalizes and
corrupts on round-trip. Add a CodeMirror-based view instead, toggled from the
prompt page actions menu, that edits the raw template verbatim.
- New shared CodeEditor (CodeMirror 6 + markdown highlighting, line wrapping,
theme-aware), lazy-loaded so its chunk only loads when code view is opened.
- "Code editor" / "Plain text" toggle in the prompt actions menu.
- Available-variables click inserts {{.Var}} into the code editor at the caret.
- Fix a pre-existing tsc error in the variable-cycling code
(noUncheckedIndexedAccess on the matched-occurrence lookup).
Round-trip verified byte-exact end to end: original -> code edit -> plain, and
save -> DB -> reload, all identical to source (tables, tags, whitespace intact).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Clicking an in-use variable in "Available variables" jumped only to the first
occurrence. Now it cycles: from the occurrence the caret is on it advances to
the next (wrapping past the last), else jumps to the first at/after the caret.
Each badge also shows a ×N count when the variable is used more than once.
Verified live (vite dev → docker backend) on the adviser prompt: a ×7 variable
steps through all 7 occurrences in order and wraps.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
FormModelComboboxItem manually glued an Input and a dropdown Button by
stripping adjacent borders/corners and juggling z-index on focus/hover.
Replace that with the project's InputGroup primitive (single border, ghost
trigger, native group focus-ring) — matching InputPassword and the ~20 other
input-group usages. Also gives the icon-only trigger an accessible name.
Verified live (vite dev against the docker backend): input editable, dropdown
opens via the asChild trigger, option/price autofill intact.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
anthropic, bedrock, and gemini also carry per-agent prices in config.yml but
were not covered. Adding them confirms no current drift and guards them going
forward. bedrock's loaders take a *config.Config, so they're wrapped with an
empty config to read the embedded catalog.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Audited all 133 catalog models across 9 providers against official pricing
pages, each delta independently re-verified. openai/anthropic/gemini/glm/kimi
were already correct (0 changes). Corrections:
- deepseek-v4-pro: 1.74/3.48/0.0145 -> 0.435/0.87/0.003625 (catalog was 4x the
official DeepSeek rate).
- bedrock mistral-large-3-675b: 4.0/12.0 -> 0.5/1.5 (8x overstatement; old
Mistral Large 24.07 rate).
- minimax M3 0.6/2.4 -> 0.3/1.2, M2.7 0.4/1.1 -> 0.3/1.2, M2.7-highspeed
0.4/1.1 -> 0.6/2.4, all +0.06 cache (permanent-50%-off effective rates).
- qwen3.6-35b-a3b: 0.248/1.485 -> 0.375/2.25 (catalog had the China-mainland
price, not the International endpoint the rest of the catalog uses).
- qwen: add cache_read = 0.20 x input (implicit-cache rule) to 16 open-source
models that were missing it.
config.yml agent prices synced for deepseek-v4-pro and MiniMax-M3 (guard test
keeps them aligned).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Verified per the official OpenAI model pages:
- gpt-5.2-codex: [low, medium, high, xhigh]
- gpt-5-pro: [high] (the page states it "only supports reasoning.effort: high")
Other openai reasoning models (gpt-5, gpt-5.1 = no xhigh; gpt-5-mini/nano,
codex variants, o-series) keep the default — their official pages do not
enumerate an accepted effort set.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Alibaba Model Studio's context-cache doc bills cached input tokens at 20% of the
input price (implicit hits, International endpoint). Most of the qwen catalog
already used 20%; align the outliers and guard against future drift.
- qwen3.7-max 1.25 -> 0.5, qwen3.7-plus 0.2 -> 0.08: corrects an earlier change
that read a "50% discount" off the model-pricing page; the authoritative rate
is 20%, so the original 0.5 for qwen3.7-max was already correct.
- qwen3.6-{max-preview,plus,flash}, qwen3.5-{plus,flash}: 10% -> 20% stale
outliers, with matching config.yml agent-price updates.
Add TestAgentConfigPricesMatchCatalog: GetPriceInfoForType returns the agent
price with no catalog fallback, so config.yml drift silently mis-prices cost.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Verified per the OpenAI model pages (reasoning.effort support):
- gpt-5.4-mini, gpt-5.4-nano, gpt-5.2: [low, medium, high, xhigh]
- gpt-5.2-pro: [medium, high, xhigh] (no low)
gpt-5 / gpt-5.1 keep the default [low, medium, high] (no xhigh; gpt-5 uses
"minimal", not representable in the UI enum). Codex variants are unverified
and left for a follow-up.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The settings effort dropdown is driven by a model's reasoning.efforts and
falls back to [low, medium, high] when absent, so xhigh/max were never
selectable for OpenAI-compatible models even though the backend accepts them.
Declare the verified accepted levels:
- glm-5.2: [high, max] (Z.AI: GLM-5.2 reasoning_effort accepts only high/max,
so the default low/medium were also wrong for it)
- gpt-5.4: [low, medium, high, xhigh] (OpenAI GPT-5.4/5.5 effort enum)
Other openai/gpt-5.x entries still need per-model effort verification.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
cache_read was 0.5; the Alibaba Model Studio official price (International)
is 1.25 per 1M tokens (a 50% discount on the 2.5 input rate). Pre-existing
inaccuracy, unrelated to the qwen3.7-plus addition.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Replace the placeholder estimates with verified list prices (USD per 1M tokens):
- kimi-k2.7-code: 0.95 / 4.00 / 0.19 cache (platform.kimi.ai official) —
identical input/output to k2.6, only the cache rate differs.
- qwen3.7-plus: 0.4 / 1.6 / 0.2 cache (Alibaba Model Studio official,
International base <=256K tier) — the earlier estimate conflated it with
the qwen3.7-max tier and was ~2.5x too high.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
"the only GLM model that honors reasoning_effort" is an unenforceable
prose claim; state the capability the entry actually carries instead.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The tail reader's no-trailing-newline branch (a torn/truncated final
append, the case M3's fsync defends) and the over-window error branch
had no coverage. Add cases for a newline-free last line, a torn final
append that must be rejected, and a single line exceeding the 64KiB
window.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The M7 pin only checked models actually assigned to an agent type, so an
adaptive reasoning mode declared on an unassigned catalog model would pass
silently. Add a second loop over every catalog model so any openaicompat
provider that declares adaptive/adaptive-only fails loudly — matching the
guard's stated intent.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The comment narrated the replaced sync.Map design and defended the
choice; the fixed-stripe array plus FNV indexing is self-evident and
the rationale already lives in commit d12b984.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- glm/models.yml: add glm-5.2 (only GLM model supporting reasoning_effort=high/max)
- kimi/models.yml: add kimi-k2.7-code (code-specialist above k2.6)
- qwen/models.yml: add qwen3.7-plus (cost-efficient tier below qwen3.7-max)
Prices for kimi-k2.7-code and qwen3.7-plus are estimated from adjacent
catalog entries and should be verified against official pricing pages.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The per-agent options builder only emitted WithReasoning for low/medium/high,
and the langchaingo fork clamped xhigh/max to high in GetEffort (treating them
as adaptive-only). OpenAI GPT-5.5 and GLM-5.2 now expose xhigh/max as real
reasoning_effort levels, so that clamp encodes a stale invariant.
Extend the effort switch to pass xhigh/max through; the fork's GetEffort clamp
is removed in the local langchaingo (propagated via vendor) so the OpenAI
transport emits the real level. Adaptive (anthropic/bedrock) and budget paths
are unaffected — GetEffort is called only by the OpenAI transport. Validity is
gated per model by ModelReasoningInfo.Efforts.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Adaptive thinking (thinking.type=adaptive + output_config.effort) is an
Anthropic-protocol mode the langchaingo OpenAI transport cannot emit, and
the openaicompat Call path never threads PrepareAdaptiveCallOptions. So an
adaptive reasoning mode declared in an openaicompat provider's models.yml
would silently no-op.
Assert that none of the openaicompat-backed providers (qwen, glm, deepseek,
kimi, minimax) resolve to adaptive thinking for any agent type. The day
someone adds an adaptive model/mode to one of their configs, this fails
loudly instead of dropping the thinking budget in silence.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
record() called readLastEvidenceReceiptHash on every append, which re-read
and re-hashed the entire receipts.jsonl just to get the last hash and verify
the whole chain — O(N^2) over a flow's receipts, on the tool-call hot path
under the per-path lock (M2).
Read only the last line instead (windowed ReadAt from the end), failing
closed if that line is missing, wrong-schema, or hash-mismatched. This is
O(1) per append and stays correct across the multiple recorder instances
that write one path (L6): the file stays the single source of truth, so
there is no per-instance cache to go stale. Full-chain verification belongs
in a separate read-time verify tool, not on every write.
Off by default (EVIDENCE_RECEIPTS_ENABLED=false). Measured: 1024 concurrent
appends under -race dropped from ~49s to ~7.5s.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The append wrote the receipt line and returned without flushing, so a crash
between the write and the OS flushing its page cache could lose or truncate
the last receipt, after which the fail-closed chain check halts all further
writes until the file is repaired (M3). Sync the file before returning.
Off by default (EVIDENCE_RECEIPTS_ENABLED=false), so standard deployments are
unaffected; the cost lands only when the feature is explicitly enabled.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Three guards for the L6 sharded mutex pool (d12b984):
- bounded: 100k distinct flows resolve to <= 256 mutexes, so reverting to a
per-path map (the original unbounded leak) fails the test.
- high concurrency: 16 cross-executor writers on one path keep the hash chain
intact under -race.
- stripe collision: two flows that hash to the same stripe keep their own
chains intact, confirming shared stripes add contention but not corruption.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
A sync.Map holding one *sync.Mutex per flow path grew unbounded for the
whole server uptime. A fixed 256-stripe array keyed by FNV-32a hash of
the path caps memory at a constant cost while preserving per-path append
serialization required by the hash-chain invariant.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Added langfuse observability support to the graphiti search tool, allowing for detailed tracking of search operations.
- Introduced a mapping of search types to human-readable titles for better traceability in logs.
- Implemented a new method to build the input payload for langfuse retrievers, encapsulating relevant search parameters.
- Enhanced error handling to include retriever status updates on success and failure, improving observability and debugging capabilities.
- Introduced a process-level singleton for the anonymizer replacer to enhance performance and ensure thread safety.
- The replacer is built once using patterns loaded at startup, allowing it to be shared across all flow executor instances.
- Updated the flow tools executor to utilize the shared replacer, simplifying the creation process and improving efficiency.
- Replaced expirable LRU cache with non-expirable lru.Cache in multiple files for improved performance and reduced resource usage.
- Introduced a new function, newSummarizerCache, to create a fixed-size LRU cache for summarizer results, eliminating the need for background goroutines.
- Updated related code to ensure compatibility with the new cache implementation.
The OAuth callback links/creates an account by the email from ResolveEmail, and
Google/GitHub only ever return a verified address — but that invariant lived
inside each provider and was invisible at the callback. A future OAuth provider
that omitted the verified check would let an attacker register a victim's email
there (unverified), "sign in", and be linked straight into the victim's account:
instant takeover.
Make verification part of the contract: ResolveEmail now returns
(email, verified, err), and the callback refuses to proceed when !verified.
Because Go's bool zero value is false and the compiler forces the new return, a
provider that forgets to report verification fails closed (its own login breaks)
rather than opening a takeover. Google reports claims.EmailVerified; GitHub only
selects verified addresses, so reports true. Added a callback test: a provider
reporting an unverified email is rejected (no link, no session) — red before the
gate, green after.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
EmailChange.Mail validated with `vmail`, which accepts not just a real address
but also the literal "admin" and any UUID — escape hatches that exist so the
seeded admin row (mail "admin") passes User.Mail's Valid(). The account's
change-email form (added this branch) reaches it, so a user could save "admin"
or a UUID as their own email — a non-deliverable value (no privilege gain: roles
come from role_id, and UNIQUE(mail) blocks colliding with the real admin row).
Add a strict `realemail` validator (same address regex as vmail, minus the
hatches) and use it for EmailChange.Mail; User.Mail keeps `vmail` so the seeded
admin still validates. Tests cover the validator (admin/UUID rejected, real
address accepted) and the handler (changing to a UUID or "admin" now 400s).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
ChangeEmailCurrentUser was the only path that lowercased the email
(strings.ToLower), while local login, the OAuth callback and CreateUser all
store/compare it raw against a case-sensitive UNIQUE(mail). That lone
normalization let a changed address (now lowercased) miss a later raw-case
login, and let the uniqueness pre-check (run on the lowercased value) skip an
existing mixed-case row. Drop the ToLower so every path is consistently
case-sensitive again — the pre-branch invariant. The email validator already
rejects surrounding whitespace, so the paired TrimSpace was dead.
Update the test that codified the old lowercasing to assert case preservation.
A fully case-insensitive scheme (normalize everywhere, or citext /
UNIQUE(lower(mail))) is tracked separately as a follow-up.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
NewProviderController loaded every provider's default config (NewConfig) in an
ungated loop that treated any error as fatal, while actual provider construction
(New) is correctly gated on Enabled. A disabled provider pointed at an unreadable
BEDROCK_CONFIG_PATH (or the equivalent custom/ollama external config) therefore
aborted startup, even though that provider was never going to be used.
Extract the config-loading loop into buildDefaultConfigs and gate the failure on
Enabled: a disabled provider whose external config can't be read is logged and
skipped; an enabled provider still fails loudly. Tests cover both paths
(disabled + bad path non-fatal, enabled + bad path fatal).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
DetailNavigationSheet keeps a local input mirror (localQuery) seeded once from
controller.searchQuery — a deliberate perf decouple (92a9e59) so typing in the
sheet doesn't re-render the whole detail page. But in the controller's documented
controlled mode (a page-level search box that owns searchQuery), an external
change made while the sheet was closed left the mirror stale: reopening the sheet
showed the old text.
Re-seed the mirror from the controller on each open, folded into the existing
open-transition reconciliation. The sheet is modal, so searchQuery can only
change externally while closed — on-open re-seeding suffices and never clobbers
in-progress typing. Add a controlled-mode test that reproduces the stale input
(red before, green after).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
renderTextWithCJK selected the CJK font via `bold ? 'NotoSansSC' : 'NotoSansSC'`
— both branches identical, so the ternary was dead. Collapse it to the single
family. The CJK detection regex matches Han, kana, Hangul and Bopomofo, but the
only registered CJK font (NotoSansSC) lacks Hangul — verified with fontkit — so
Korean renders as missing-glyph boxes; document that limitation and the
NotoSansKR fix path.
splitByCJK and renderTextWithCJK had no tests; add a suite covering segmentation
(mixed Latin/CJK, kana, hangul, CJK punctuation, empty input) and per-segment
font assignment.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The DetailNavigationSheet virtualized branch (items.length > 100) was never
exercised — the fixture had 4 items, always below the threshold. Add a 150-item
suite covering the virtualized path: a windowed subset of options, the roving
tabIndex on the current option, and in-window ArrowDown navigation. The
@tanstack virtualizer can't measure a viewport under jsdom, so the hook is mocked
to a fixed window (the windowing math is @tanstack's own coverage).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The provider model field is an Input + dropdown combobox. Picking from the
dropdown (or "Use as custom") fires onOptionSelect, which resets price/reasoning
to the new model's catalog values — but typing the model name only updated the
field, leaving stale price/reasoning from the previously-selected model. Fire
onOptionSelect from the Input's onChange when the typed value exactly matches a
catalog option, so a typed known model behaves like a picked one.
Live-verified: typing us.anthropic.claude-sonnet-4-5-... into an agent on
gpt-oss reset Input Price 0.15->3, Output 0.6->15, cache 0->0.3/3.75.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
From a doc-grounded review against @apollo/client 4.2.3 + graphql-ws 6 (all
findings low/info, adversarially verified):
- streaming link: fold the throttle timestamp into the LRU StreamingLogEntry so
it is evicted with its log — removes the unbounded lastUpdateTimestamps Map
that leaked for streams that never receive a closing (non-appendPart) message.
- errorLink: also dispatch auth:refresh on a ServerParseError 401/403 (the narrow
application/graphql-response+json path that ServerError.is() does not match).
- WS retryWait: add jitter so a mass reconnect (e.g. backend restart) does not
thundering-herd the server.
- cache: log instead of silently swallowing a storeFieldName parse failure in
matchesCacheVariant, so a future Apollo serialization change is observable.
- v4 deprecations: onError -> new ErrorLink, createHttpLink -> new HttpLink,
FetchResult -> ApolloLink.Result, Operation -> ApolloLink.Operation.
Verified: tsc -b + vite build, 604 vitest pass, and a live smoke on the docker
stand (queries + subscription WS connect, no auth/JS errors).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The subscription WebSocket retries forever on a 403 handshake (expired/invalid
cookie), but its error handler only escalated to auth:refresh when the error
*message* contained "403"/"auth required" — and browsers never expose the
handshake HTTP status on a WebSocket error event, so that detection never fired.
An idle page with active subscriptions therefore looped on 403 with no redirect
to login (the redirect only fired once a REST/axios call hit a 403). Dispatch
auth:refresh unconditionally on any WS error and let /info decide: it redirects
on a real 401/403 and is a no-op while the session holds. Live-verified both
ways: an invalid cookie now redirects to login from an idle page, and a
transient WS drop on a valid session keeps the user logged in. Pre-existing (the
WS handler is unchanged from main); surfaced by a tester.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Address the container escape risk reported in issue #337 (Docker socket
bind-mount when DOCKER_INSIDE=true).
Changes:
backend/pkg/docker/client.go — RunContainer hardening
• Add `no-new-privileges:true` to SecurityOpt on every sandbox container.
Prevents setuid/setgid and file-capability escalation inside the sandbox.
• Add PidsLimit=2048 as a cheap fork-bomb / resource exhaustion guard.
• Add startup warning (logrus.Warn) when DOCKER_INSIDE=true so operators
see the socket-escape risk at boot rather than only in documentation.
• Correct the comment to not imply the socket-escape vector is mitigated
by no-new-privileges alone (it is not; the real fix is DOCKER_INSIDE=false
or a least-privilege socket proxy).
backend/pkg/tools/tools.go — CapDrop ALL on primary terminal container
• Drop all Linux capabilities then add back only NET_RAW (always) and
NET_ADMIN (when DOCKER_NET_ADMIN=true). Removes ~14 unnecessary caps
from the default Docker set (e.g. SYS_CHROOT, AUDIT_WRITE, MKNOD) that
pentest tools should not need and that could be abused in an escape chain.
.env.example
• Flip DOCKER_INSIDE default to false (aligned with config.go envDefault).
The previous example was contradicting the code default.
• Expand the DOCKER_INSIDE comment: explains socket-escape risk, DinD
guidance, and links to docker-socket-proxy as a least-privilege alternative.
Note: DOCKER_INSIDE=false is the safest configuration; operators who need
DinD should consider fronting /var/run/docker.sock with a proxy rather than
mounting it directly.
The "Frontend - Install dependencies" step ran pnpm install --frozen-lockfile
with continue-on-error: true, swallowing the ERR_PNPM_OUTDATED_LOCKFILE that the
flag exists to raise. The rest of the frontend pipeline (prettier, lint,
type-check, test) already gates strictly, so a stale pnpm-lock.yaml would only
surface later as a confusing downstream "command not found". Drop the flag so
lockfile drift fails loudly at the install step. Backend steps left as-is.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A type present in only one of the two hand-maintained lists fails silently:
accepted by the API then erroring "unknown provider type" at construction, or
rejected 422 despite working. Assert set-equality and canonical names so drift
fails in CI instead.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
UsesAdaptiveThinking/PrepareAdaptiveCallOptions had no test coverage after the
native-langchaingo migration removed the old transport-layer tests. Add table
tests: an adaptive-only model forces adaptive over an agent's budget choice or an
absent reasoning block, while budget-only models stay untouched.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The four Zip* builders deferred zw.Close() with an unnamed return, dropping the
error from the central-directory flush. After the resources download moved to
direct socket streaming, a dropped connection during that final flush could
return a truncated archive under HTTP 200. Capture Close() via a named return so
streamZipArchive logs and aborts the partial response. Regression tests in both
packages drive the Close() error path with a failing writer.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- settings-provider: handleTest/handleTestAgent/onSaveAndLeave now reset
submitError before re-validating. The error toast is driven by a
submitError-change effect, so a repeated identical validation failure
previously set the same string and never re-fired; the await between the
reset and the re-set splits the React batch so the toast shows every time.
- settings-prompt: the variables palette marks "used" chips with a leading
check icon, giving a non-color signal alongside the green variant (the
used/available distinction was conveyed by hue alone for sighted users).
- settings-sidebar: drop the unused `export` on the MenuItem interface — it has
no importers; the extraction from settings-layout was the moment to clean it.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The provider and prompt edit pages each carried a bespoke unsaved-changes
mechanism: a synthetic history.pushState + popstate listener that only caught
the browser back gesture, a "Discard changes?" ConfirmationDialog, and (after
the in-page Cancel button was dropped in the redesign) a chunk of unreachable
leave-handler code. In-app sidebar navigation while dirty silently discarded
edits, and the discard dialog rendered a Trash icon via confirmIcon={undefined}.
Both pages now use the same useUnsavedChangesGuard + UnsavedChangesDialog the
knowledge editor uses:
- useBlocker intercepts in-app router navigation (the sidebar links), and
beforeunload covers reload/tab-close — not just the back gesture.
- The dialog offers Cancel / Discard / Save & leave (the old one was Stay /
Leave with no save path).
- Forms switch to mode: 'onTouched' so isValid drives the dialog's Save button.
- Provider keeps "Save navigates to the list" via the guard's skipNextBlock;
prompt's Save & leave saves every dirty tab (snapshotting both before the
refetch-driven reset can clobber the other tab).
Removes the popstate/pushState refs, the dead handleConfirmLeave/-OpenChange
branches, and the misleading Trash icon. Resolves review findings on the
removed Cancel affordance, the dead leave-guard code, and the discard icon.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A code review of the "Available variables" block surfaced several real issues:
- Used-detection only matched bare {{.X}} interpolations, so variables used
only in conditionals/ranges/nested access ({{if .X}}, {{range .X}}, {{.X.Y}})
showed as "available" and clicking them inserted a stray bare {{.X}} instead
of jumping to the existing usage. Detection and the click-to-locate logic now
share one regex matching a top-level field in any {{ }} action, mirroring the
backend's variable extraction; clicking a used variable selects its real
occurrence.
- Clicking a used variable scrolled to it by counting logical newlines, which
undershot badly once the textarea soft-wraps long lines (the default
templates lay out ~40% more visual lines than logical), so the jumped-to
variable landed off-screen. Measure the true pixel offset through a hidden
mirror element and center it, so the selection is always scrolled into view.
- Inserting a variable via a chip called setValue without { shouldDirty: true },
so the change never marked the form dirty and the unsaved-changes guard stayed
silent. Both insert paths now mark the form dirty, matching keyboard typing.
- The chips were click-only <div>s (no keyboard/screen-reader access). They are
now role="button" with tabIndex, Enter/Space handling, and a state-aware
aria-label/title ("Insert …" / "Go to …"), which also activates the Badge's
existing focus ring.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The "Available variables" block merged into the background on desktop and the
hand-rolled chips used light-theme greens (bg-green-100/text-green-800) that
clashed with the dark UI. Rebuild it on the project's primitives:
- Container: a delineated `rounded-lg border bg-card` panel with a `border-b`
header (title + "click to insert" hint); the chips sit in a recessed
`bg-background` tray below it, so the section reads as a distinct group with
depth instead of a faint box.
- Chips: the shared `Badge` component — `green` (theme-aware) for variables
already used in the template, `secondary` for the rest; monospace, normal
weight, clickable.
- Badge: give the color variants (blue/green/orange/pink/purple/red/yellow)
hover states to match default/secondary/destructive, so consumers don't
hand-roll hover colors.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Extract the "Available Variables" panel out of promptMeta into its own
`variablesPanel`. Desktop keeps it in the left pane under the tab selector
(reference beside the editor); mobile now renders it after the editor instead of
between the tabs and the editor, so the template editor sits directly under the
tabs on small screens.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The provider, knowledge and prompt edit pages share one 2-pane shell, but
mobile and the intro block had drifted. Align them:
- Mobile: drop the wrapping Card on provider + knowledge (knowledge-form-layout,
settings-provider) so all three render the stacked form directly in
`flex min-h-0 flex-1 flex-col gap-4 p-4` (matches the prompt page; gap-4 to
match the p-4 edge padding).
- Intro: use a `flex flex-col gap-2 text-center` wrapper with
`<h2 class="text-2xl font-semibold">` + a `text-muted-foreground` description
everywhere — knowledge was an `<h1>`, the prompt used `items-center gap-1`, and
both leaned on a `mt-2` margin instead of the container gap.
Desktop shell (root, ResizablePanelGroup 45/55, left Card + CardContent py-6,
grip handle, per-pane scroll) was already uniform. The right-pane content stays
page-specific (accordion / markdown editor / textarea).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Mirror the knowledge/provider edit pages: replace the single-column form +
sticky footer with a responsive 2-pane layout (desktop ResizablePanelGroup,
mobile single column). Left pane = centered intro + prompt identity + the
System/Human tab selector + the variables palette; right pane = the template
editor that fills the panel.
Move actions into the AppHeader: Validate + Save, plus an ellipsis menu (Reset,
Diff) shown only when a user override exists — no Cancel. Convert the inline
error alerts to a single submitError-driven toast, and the loading/error/
not-found branches to StatusCard. Drop the now-unused handleBack.
Shared UI tweaks supporting the editor:
- Textarea: add an `autoSize` opt-out (default true) so the editor can flex-fill
its parent (the auto-size hook's inline max-height otherwise clamps it).
- TabsTrigger: add `gap-2` (matches Button) so an icon + label aren't glued.
Align the panel/Card structure with the knowledge layout (py-6 intro,
overflow-y-auto left, overflow-hidden fill-editor right, grip handle, 45/55
split); style the tab bar like the dashboard analytics tabs (bg-background list
+ bg-card active, full-width flex-1 triggers).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Introduce a shared AppHeader compound family (AppHeader / AppHeaderAction /
AppHeaderActions / AppHeaderContent / AppHeaderTitle) in a single module and
fold the page-header action button into it as AppHeaderAction (renamed from the
former HeaderButton). Every page header now composes this family instead of
copy-pasting the sticky <header> shell:
- settings pages (account, api-tokens, prompt(s), provider(s))
- main-app lists (dashboard, flows, templates, resources, knowledges, new-flow)
- detail headers (flow, template, knowledge) keep their bespoke breadcrumb
content as AppHeaderContent children; their action clusters move into
AppHeaderActions; sibling sheets/dialogs stay outside the header
This removes the duplicated shell across ~15 sites and the drift between copies
(the family owns the one canonical sticky shell + the SidebarTrigger/Separator).
Reorganize components/layouts into per-area subfolders:
- app/ app-layout + the AppHeader family (app-header.tsx)
- main/ main-layout, main-sidebar (+ test)
- settings/ settings-layout, settings-sidebar (+ test)
- flows/ flows-layout
Delete settings-page-header.tsx (superseded by AppHeader).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Rebuild the provider settings page to match the knowledge editor:
- responsive 2-pane layout — left Card with the centered intro + Type/Name,
right scrollable panel with the agent-config accordion; mobile collapses
to a single-column Card (via useBreakpoint). Each pane scrolls
independently inside a fixed-height root (no whole-page scroll).
- move Save / Test / Delete into the page header (SettingsPageHeader actions);
drop the sticky-bottom action bar and the now-unused Cancel/handleBack.
- surface mutation/validation errors as sonner toasts instead of inline
Alerts (single submitError-driven effect).
- redesign the test-results modal: shrink-0 status icon, result/metadata as
badges, wrapping monospace error block, colored per-agent pass count.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Mirror the main app layout: SettingsLayout now renders only
SidebarProvider + SettingsSidebar + SidebarInset + Outlet, with no shared
header. Each settings page renders its own header via a new shared
SettingsPageHeader (sticky h-12 bar with an optional actions slot). The
sidebar is extracted into a self-contained SettingsSidebar component that
computes the "Back to App" returnUrl from location.state; its behavior is
covered by the new settings-sidebar.test (migrated from the removed
settings-layout.test). settings-account.test now wraps the page in a
SidebarProvider since the page renders its own SidebarTrigger.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Adaptive thinking (Claude Opus 4.7+) is now implemented natively in the
vxcontrol/langchaingo fork (v0.1.14-update.6): the anthropic and bedrock clients
emit thinking.type=adaptive + output_config.effort and omit the sampling params
adaptive models reject. PentAGI no longer patches the serialized request body.
- pconfig.PrepareAdaptiveCallOptions appends llms.WithAdaptiveReasoning; the
ctx-effort plumbing (WithAdaptiveEffort/AdaptiveEffortFromContext) is removed.
- Delete the bedrock smithy Build middleware and anthropic http RoundTripper
(adaptive_thinking.go + tests in both packages) that rewrote the request body.
- Bump the langchaingo require to v0.1.14-update.6; refresh llms_how_to.md.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
pnpm 11 installs globally-added binaries to $PNPM_HOME/bin and treats that
directory being absent from PATH as a hard error, so `pnpm add -g license-checker`
in the frontend-compiler stage failed ("global bin directory is not in PATH")
whenever the frontend layer cache was invalidated. Prepend $PNPM_HOME/bin to PATH.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
settings-providers.tsx redeclared its own ProviderType→icon map (and imported all
11 icon components) duplicating the registry already in provider-icon.tsx. Export
that map and consume it here, dropping the duplicate map and the 11 icon imports.
providerLabels/providerTypes stay (labels, single-use). No visual change — the
icons still render monochrome at their existing sizes.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The provider controller repeated every provider type across five hand-written
blocks (default-config wiring, key-gated instantiation, GetProvider fallback,
NewProvider, buildProviderFromConfig) plus the API-layer Valid() whitelist.
Introduce pkg/providers/registry.go: a providerRegistry table whose entries hold
the per-type constructors and credential gating, with small adapter helpers
(ignoreConfig/fromData) absorbing the signature variance (bedrock/ollama/custom
take *config.Config; the rest don't). The controller now wires and looks up
providers in loops over the table. Valid() validates against the new canonical
provider.AllProviderTypes list (no heavyweight import, no cycle).
Adding a provider's backend wiring drops from ~6 edits across these functions to
one registry entry. providers.go shrinks ~300 lines; behavior is unchanged
(same exported funcs, same gating) and all provider/server/graph tests stay green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
deepseek/glm/kimi/qwen/minimax were near-verbatim clones — identical struct +
13 interface methods, differing only in constants, env accessors, and two flags.
Extract pkg/providers/openaicompat with a Spec + a shared Provider implementing
the interface; each provider now keeps only its constants, embedded config/models,
the Default*/Build* loaders, and a thin New() that delegates to openaicompat.New.
Each provider file drops from ~190 to ~78 lines with zero behavior change (same
exported funcs; per-provider tests stay green). The native openai provider is
intentionally left separate (no model prefix / reasoning-preservation).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The added Claude/Bedrock rows put "✅ adaptive-only" in the narrow Thinking
column, which broke the source pipe alignment of the carefully-padded tables.
Use a plain ✅ in the Thinking column (the adaptive-only detail already lives in
the Use Case text and the Adaptive Thinking note) and re-pad the rows so the
columns line up again.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Review nits:
- schema.resolvers.go: log (not swallow) bedrock.DefaultModels errors so an
invalid BEDROCK_MODELS_PATH no longer yields a silently-empty model list.
- settings-providers.tsx: derive the create-provider type list from an
exhaustive Record<ProviderType,string> so a future ProviderType is a compile
error here instead of silently missing from the menu.
- trim two doc comments (convertModelReasoningMode, ReasoningFields) to lead
with the load-bearing contract instead of restating the name.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The bedrock and anthropic adaptive_thinking.go files carried ~96 byte-identical
lines (prepareCallOptions, usesAdaptiveThinking, modelReasoningMode,
reasoningConfigForType, agentConfigForType, the effort context key), and
agentConfigForType was a third copy of the agent-type switch pconfig already
owns in GetPriceInfoForType.
Move the model-agnostic logic onto pconfig.ProviderConfig:
AgentConfigForType (now also backing GetPriceInfoForType), UsesAdaptiveThinking,
PrepareAdaptiveCallOptions, and the WithAdaptiveEffort/AdaptiveEffortFromContext
context helpers. Each provider now keeps only its transport-specific pieces:
the smithy Build middleware (bedrock) / http RoundTripper (anthropic) and
rewriteAdaptiveThinkingBody. Also drop the dead delete(payload,"top_k") in the
anthropic rewrite — langchaingo's Messages payload only serializes
temperature/top_p. Backstop tests rewired to the pconfig API; all provider tests
+ go vet pass.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Code review found the providers were fully wired in code but missing from
several user-facing surfaces:
- MiniMax (#328): add to .env.example, docker-compose env passthrough,
backend/docs/config.md env table, README provider list + a MiniMax
configuration section, and backend/docs/database.md PROVIDER_TYPE enum.
- Claude Opus 4.7/4.8 (#288): add to the README Claude and Bedrock model
catalogs and correct the model counts (10→11 Claude, 21→24 Bedrock); note
4.7/4.8 are adaptive-thinking-only in the Adaptive Thinking section.
- llms_how_to.md: scope the "Temperature=1.0" rule to budget thinking and add
an adaptive-thinking caveat (4.7/4.8 reject sampling params), so the guide no
longer contradicts the shipped adaptive code path.
- docker-compose: point the Bedrock config/models default mount at the tracked
examples/configs/bedrock-glm-flash.* files (the README-documented path) so a
plain `docker compose up` no longer creates empty placeholder directories.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Three QA-found edge cases in the provider form:
- Choosing "Use <x> as custom" set the model without running onOptionSelect, so
reasoning/price stayed stale for the typed model. Fire onOptionSelect with the
synthetic option so they reset like a dropdown pick.
- Selecting effort max/xhigh on an adaptive-capable model with mode unset left
the backend with no way to route the reasoning (it dropped it). Auto-set mode
to Adaptive, since max/xhigh are adaptive-thinking effort levels.
- Add zod cross-field refines (minLength<=maxLength, reasoning.maxTokens<=32000)
that native HTML5 validation can't express, mirroring the new backend checks.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The GraphQL createProvider/updateProvider path applied no field validation, so
a direct API call (bypassing the browser's native HTML5 form validation) could
persist nonsensical values (temperature 99, negative price, an inverted
min/max length window, a reasoning budget over the 32000 engine cap).
Add ProviderConfig.Validate()/AgentConfig.Validate(), called after
patchProviderConfig in both CreateProvider and UpdateProvider. It is deliberately
permissive — 0 means "unset" and provider-specific tuning ranges remain the LLM
API's responsibility — so it only rejects universally-invalid values and never a
valid provider-specific config. Found during comprehensive provider QA.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The QA audit found minimax was wired into production everywhere but omitted
from provider-enumeration test data, so a future regression dropping it would
go uncaught. Add minimax to ProviderType.Valid()'s validTypes table, to the
GetSecretPatterns config (expected count 29→30, exercising the "MiniMax Key"
redaction pattern), and to clearConfigEnv's hermetic env list.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
onOptionSelect reset reasoning.mode and reasoning.effort when the agent model
changes but left reasoning.maxTokens untouched, so a budget token value set for
a previous model leaked into the next one (e.g. switching from a budget-capable
model to an adaptive-only model kept the stale value in the form). Reset it
alongside mode/effort. Found during comprehensive provider QA.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Reworks external PR #328 (octo-patch). The PR added only the provider core;
this brings MiniMax to full parity with the other providers (qwen) so it is
selectable and configurable in the UI and installer.
Applied from the PR (verified against MiniMax's official API docs — M3/M2.7/
M2.7-highspeed are real current models; corrected the M3 description from the
PR's "512K" to the documented ~1M context):
- minimax provider package (OpenAI-compatible https://api.minimax.io/v1),
config.yml, models.yml, tests; MINIMAX_API_KEY/SERVER_URL/PROVIDER env vars;
ProviderMiniMax type + DefaultProviderNameMiniMax; providers.go wiring;
Valid() whitelist.
Added for completeness:
- goose migration adding 'minimax' to the PROVIDER_TYPE enum + database
ProviderTypeMinimax const.
- GraphQL: minimax in ProviderType enum, ProvidersModelsList,
ProvidersReadinessStatus, DefaultProvidersConfig; resolvers wire default
config/models + enabled status; gqlgen regenerated.
- Frontend: MiniMax icon (lobehub), provider-icon + settings-providers
registration + provider type list; regenerated GraphQL types.
- Installer wizard: provider form, screen, list, registry, env-var mappings,
locale strings + help text.
- ctester/ftester: -type/-provider minimax support.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The ReasoningFields mode/effort selects used `defaultValue`, making them
uncontrolled — Radix reads it once on mount, so the `setValue` resets in
onOptionSelect (reset reasoning on model change) updated form state but never
the visible selection. Result: after switching models the selectors showed
stale values (e.g. mode "Adaptive" when the field was cleared to null; effort
left blank when a stale 4.7/4.8 "xhigh" had no item under opus-4-6). Switch to
controlled `value` so the display follows the reset. Also drop a dead
empty-comment block in onOptionSelect.
Found during Layer 3 live verification on the docker stack.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The component declared control as Control<FormData> (z.output, required
name/type) but receives the form's Control<FormInput> (z.input, optional
name/type), which `tsc -b` (the production build typecheck) rejects with
"Type 'undefined' is not assignable to type 'string'". `tsc --noEmit -p
tsconfig.json` did not catch it; `pnpm run build` (tsc -b && vite build) now
passes.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Closes audit-found coverage gaps:
- bedrock: TestBackstopForcesAdaptiveForAdaptiveOnlyModel (adaptive-only model
forces adaptive with no agent reasoning block) + a negative case for a
non-reasoning model. The Anthropic backstop already had an httptest test;
Bedrock had none.
- pconfig: ReasoningConfig.EffectiveMode (incl. max_tokens->budget inference)
and IsZero.
- converter: ConvertModels reasoning mapping (pconfig adaptive-only ->
GraphQL adaptive_only, efforts passthrough, nil for no descriptor).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Switching an agent's model left the prior reasoning.mode/effort in the form
(onOptionSelect only reset price), so a stale budget mode or an effort the new
model doesn't support could be persisted. Now the model picker also resets
reasoning: adaptive-only models lock to adaptive, others clear mode + effort.
Verified: tsc --noEmit + eslint clean.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Ports the per-agent reasoning UI to support adaptive thinking, gated by each
model's declared capability (the reasoning fragment) instead of a model-name
regex:
- new ReasoningFields component: a reasoning Mode select (adaptive | budget,
shown only for adaptive-capable models, locked to adaptive for adaptive-only)
and an effort select whose options follow the model's allowed efforts
(incl. xhigh/max).
- getReasoningEffort handles xhigh/max; getReasoningMode + the form schema and
transformFormToGraphQL carry the chosen mode through to the API.
Verified locally: tsc --noEmit and eslint clean. Runtime verification on the
stack (Layer 3) is the next step.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Extends adaptive-thinking support from Bedrock to the direct Anthropic provider.
langchaingo emits only budget thinking, so adaptive is applied by rewriting the
request body — for Anthropic via an http RoundTripper (the Messages API carries
thinking and sampling params at the top level), wired through the injectable
http.Client. prepareCallOptions forces adaptive for adaptive-only models (the
models.yml capability descriptor is the single source of truth) and stashes the
effort in context for the transport.
- adaptive_thinking.go: RoundTripper + rewrite (thinking->adaptive,
output_config.effort, display=summarized, strip temperature/top_p/top_k).
- models.yml: add claude-opus-4-7 / claude-opus-4-8 (adaptive-only) + reasoning
descriptors on the adaptive models (4.6/sonnet-4.6).
- Verified by a credit-free httptest integration test asserting the rewritten
body on the wire; the shape is also accepted by the real Anthropic API. Full
live e2e pending account credits/model access.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
ModelConfig has custom UnmarshalYAML/UnmarshalJSON/MarshalYAML/MarshalJSON that
map fields by hand, so the reasoning capability descriptor added earlier was
silently dropped on load (Reasoning stayed nil). That made the Bedrock
adaptive-only backstop a no-op (modelReasoningMode never saw adaptive-only).
Handle `reasoning` in all four marshalers, mirroring `price`, plus a round-trip
regression test. Found via the anthropic adaptive integration test.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Adds reasoning { mode efforts } to the modelConfigFragment and regenerates
GraphQL types, so the provider settings UI can gate the reasoning mode/effort
controls by each model's declared capability (ModelReasoningMode incl.
adaptive_only) instead of a model-name regex.
Groundwork for the adaptive-thinking settings UI port.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Adds ModelReasoningInfo (mode + allowed efforts) to the GraphQL ModelConfig so
the frontend can gate the reasoning mode/effort UI by each model's declared
capability instead of a model-name regex. New ModelReasoningMode enum
(budget | adaptive | adaptive_only) mirrors the models.yml descriptor; the
converter maps pconfig adaptive-only -> GraphQL adaptive_only.
Backend groundwork for the Layer 2 frontend adaptive-thinking UI.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Makes adaptive-thinking models usable safely and adds Opus 4.7/4.8 to the
catalog so they are selectable and configurable.
- middleware: strip temperature/top_p/top_k and set thinking.display=summarized
when rewriting to adaptive. Opus 4.7+ reject sampling params (AWS: "no longer
supported", 400) and default display to "omitted" (empty reasoning text).
- models.yml: add us.anthropic.claude-opus-4-7 and us.anthropic.claude-opus-4-8,
plus a ModelReasoningInfo capability descriptor (mode + allowed efforts) on the
adaptive models (4.6/4.7/4.8/sonnet-4.6).
- provider backstop: force adaptive for adaptive-only models (Opus 4.7/4.8)
regardless of agent config, so selecting them cannot 400 on budget thinking.
The capability descriptor is the single source of truth (no model-name regex).
Verified: unit tests cover the body rewrite (sampling strip + display); a live
Bedrock run of the adaptive path on us.anthropic.claude-opus-4-6-v1 passed 21/23
(the 2 failures were 429 throttling, not the mechanism). Opus 4.7/4.8 could not
be exercised live -- this AWS account lacks model access (403), not a code
issue; their correctness rests on the AWS docs + the 4.6 live run + unit tests.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Integrates the backend half of PR #288 onto our branch (the frontend is
reworked separately in our codegen style), 3-way merged so the #233
config/models-path changes are preserved:
- adaptive_thinking.go: smithy Build middleware that rewrites the langchaingo
Converse body from thinking{type:enabled,budget_tokens} to
thinking{type:adaptive} + output_config.effort, wired via WithAPIOptions and
prepareCallOptions in Call/CallEx/CallWithTools.
- pconfig: ReasoningConfig.Mode (adaptive|budget) + EffectiveMode/IsZero.
- GraphQL: ReasoningMode enum, reasoning.mode field, xhigh/max effort levels.
Drops the dead llms.WithMetadata adaptive branch from AgentConfig.BuildOptions
(nothing reads opts.Metadata on the Bedrock path; adaptive is applied per-call
by the provider) and updates the unit test accordingly.
Hardening still pending (next commit): strip temperature/top_p/top_k and set
display:summarized for adaptive requests, add Opus 4.7/4.8 catalog entries with
a model reasoning-capability descriptor + force-adaptive backstop, and a live
Bedrock repro. Until then Opus 4.7 should not be selected for an agent.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Reworks PR #233 to follow the existing config-path pattern and make an
externally-added Bedrock model fully usable from the web UI.
- BEDROCK_CONFIG_PATH: replace the embedded per-agent config (model
assignments + prices), mirroring OLLAMA_SERVER_CONFIG_PATH /
LLM_SERVER_CONFIG_PATH. DefaultProviderConfig now takes *config.Config
and reads the external file when set, else the embedded config.yml.
- BEDROCK_MODELS_PATH: merge an external model catalog onto the embedded
models.yml so new ids appear and are selectable under Settings ->
Providers. DefaultModels now takes *config.Config and the resolver +
provider construction pass it through; new ids are added, a matching
name overrides the embedded entry.
Wires both through docker-compose, .env.example, config.md and the README,
and ships examples/configs/bedrock-glm-flash.{provider,models}.yml using the
real AWS Bedrock id zai.glm-4.7-flash (In-Region, no inference-profile
prefix, 4K max output).
Dropped from #233: the ProviderConfig.Name field and the SeedDefaultProviders
mechanism (a per-user DB write fired on startup and inside the read-only
SettingsProviders resolver) -- the config already reaches the UI through
DefaultProvidersConfig without any DB rows.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Reworks PR #332 to follow the repo's provider-doc convention instead of
its README-marketing form:
- add examples/configs/atlas.provider.yml, modeled on the existing
aggregator example configs (deepinfra/openrouter/novita)
- list Atlas Cloud in the README aggregators line
- LLM_SERVER_PROVIDER left EMPTY for direct access — it is a LiteLLM
model-name prefix, and #332 incorrectly recommended `openai`, which
would break /models discovery for Atlas's vendor-prefixed model ids
Dropped from #332 (not matching any existing aggregator's docs): vendor
logo/banner, UTM-tracked links, and the static 59-model table.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The documented "minimum 12 characters" and "common weak passwords
prohibited" did not match the enforced policy. Both backend
(strongPasswordValidatorString / `stpass`) and frontend (zod schema in
password-change-form.tsx) enforce: 8-100 chars, valid if 16+ chars OR
8-15 chars with a number, lowercase, uppercase, and special char from
!@#$&*. No common-password denylist exists in code.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- Use the package-path form for the tester utilities
(go run ./cmd/ctester, go run ./cmd/etester test) instead of shell
glob / single-file invocations, which are more portable and avoid the
multi-file compile pitfall.
- Add -verbose to the container etester example so it matches the local
example.
- Wrap the new README Quick Start pointer across multiple lines; rendered
Markdown is unchanged.
Issue #61 asked for a proper guide on how to start using PentAGI. A
first-use guide (How to Use PentAGI After Login) already covers what to
do after login, but the maintainer kept the issue open until an article
about installing and configuring the product is published.
Add examples/guides/installation_configuration.md, a concise ordered
walkthrough that connects the existing detailed README sections into a
single path: choose installer vs manual Docker Compose, set core server
variables (PUBLIC_URL, CORS_ORIGINS, security vars), configure and test
an LLM provider with ctester, configure and test the embedding provider
with etester, optionally add search providers and the Graphiti/Langfuse/
observability stacks, then start and verify the stack and change the
default admin password. It ends with a quick checklist and links forward
to the existing post-login usage guide.
The guide links to the relevant README reference sections rather than
duplicating them. A single pointer link is added at the top of the
README Quick Start section for discoverability.
Docs only. No installer behavior, runtime code, env vars, or schema
changes. Every environment variable named in the guide already exists in
.env.example and backend/pkg/config/config.go.
Add a troubleshooting subsection to the Embedding Configuration and
Testing section for the common case where a flow starts but then waits
indefinitely with no subtasks progressing. As noted on the issue, this
is frequently caused by a misconfigured or unreachable embedding
provider rather than by the flow itself.
The subsection points users to "docker logs pentagi" as the first
check, to the etester "test" command to validate the embedding provider
and database connection without starting a flow, and to the specific
.env settings to verify (EMBEDDING_PROVIDER, EMBEDDING_MODEL,
EMBEDDING_URL, EMBEDDING_KEY, the LLM-provider fallback, PROXY_URL, and
HTTP_CLIENT_TIMEOUT). Documentation only: no new environment variables,
no provider default changes, and no code or test changes.
Refs #322
Address review feedback on PR #325: capitalize SGLang to match the
project's name and clarify that tool calling and function calling
refer to the same capability.
Refs #309
Add a troubleshooting subsection to the Docker Image Configuration
section explaining that "failed to select primary docker image via llm
call" (older versions: "failed to get primary docker image") is raised
when PentAGI's first LLM call fails during image selection, not when
Docker or the registry is unhealthy. Points users to PentAGI and LLM
backend logs, provider URL/key/model verification, and tool-call parser
configuration for custom/OpenAI-compatible/vLLM/sglang backends.
Disabled-by-default audit feature (EVIDENCE_RECEIPTS_ENABLED): appends a
hash-chained JSONL receipt per finished/failed toolcall under
<DATA_DIR>/flow-<id>/evidence/receipts.jsonl, recording toolcall
provenance plus SHA-256 hashes of args/result (no raw content).
Integration adapted to current main: the original PR built the receipt
from a database.Toolcall returned by ce.db.UpdateToolcall*Result, which
the executor no longer uses after the ToolCallLogProvider (tclp) refactor.
Receipts are now built from the in-scope toolcall data at the tclp log
sites and recorded non-fatally, so a receipt failure is logged and never
fails an otherwise-successful toolcall.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The "failed to select primary docker image via llm call" symptom was
attributed to tool-call parser failures, but image selection is a plain
text completion (providers.go: prv.Call -> WrapGenerateFromSinglePrompt),
not a tool call. That error is a generic LLM-backend failure of the
`simple` agent type and is already covered in its own README section.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Issue #313 reported flows that stall after a few steps when running a
custom OpenAI-compatible backend (LiteLLM in front of llama.cpp serving
qwen3.6-35b via LLM_SERVER_*). The backend returned malformed tool-call
arguments, surfaced as 'Failed to parse tool call arguments as JSON'
HTTP 500s and cascading retries. The maintainer fixed the stall in the
latest build by sanitizing wrong function-call arguments.
Add a troubleshooting subsection under Custom LLM Provider Configuration
that explains the root cause and how to diagnose it:
- Custom OpenAI-compatible backends must return valid tool-call
(function-call) JSON; llama.cpp, SGLang, and vLLM usually require a
specific tool-call parser and matching chat template, and not every
setup produces valid tool calls out of the box.
- Symptoms: 'Failed to parse tool call arguments as JSON', flow stalls,
looping tool calls, the 'failed to select primary docker image via
llm call' start-of-flow failure, and unexpected backend HTTP errors.
- Investigation: check PentAGI and backend/proxy logs, validate with the
ctester utility before a full flow, confirm the parser/chat template
match the model, and update PentAGI (recent builds sanitize malformed
function-call arguments).
Docs only. No tool-call parser code, provider runtime, schema, migration,
or config-default changes. Wording frames compatibility as dependent on
the backend's OpenAI-compatible tool-call behavior rather than claiming
every llama.cpp backend is supported.
Commit the ZIP response status and headers lazily, on the first byte written, via a small zipStreamWriter. A build failure before any output now returns the normal structured error response instead of a committed 200 with a truncated body; mid-stream failures still abort. Also check the reader Close error in the helper test and cover the pre-stream failure path.
DownloadResource and DownloadFlowFile built the entire ZIP archive in a bytes.Buffer before sending it, so heap usage scaled with archive size and a few concurrent large-directory downloads could exhaust process memory.
Stream the archive straight to the response writer via a shared streamZipArchive helper; the existing ZipResources/ZipDirectory/ZipRelativePaths helpers already accept an io.Writer. Responses are now chunked (no Content-Length) and memory stays proportional to one file's copy buffer.
Address Copilot review on PR #350: note that default_backend selects a crawl backend and passive extractors such as jsfinder are not selectable there; model scope_decision as a decision plus reason in both the field list and the JSON example; add an illustrative scope_entries example and clarify when allowed_hosts applies.
Refs #336
Add examples/proposals/headless_crawler_integration.md, a docs-only RFC proposing an optional, tool-agnostic crawler / URL discovery capability for PentAGI agents. Candidate backends are katana, crawlergo, rad, and jsfinder, framed as candidates with no mandatory default. The RFC keeps dictionary fuzzing (ffuf/dirsearch) unchanged, defines structured discovery artifacts (URLs, forms, parameters, JavaScript endpoints, status codes, source page, depth, scope decision), and keeps crawler URL discovery separate from the BrowserOS MCP interactive browser backend.
Refs #336
Add examples/proposals/kubernetes_deployment.md, an RFC-style design
surface responding to the Kubernetes deployment request in #324. The
document is docs-only: no Helm charts, manifests, operator, compose,
installer, or environment-variable changes, and it does not claim
Kubernetes is supported today.
It records the current Compose/installer deployment assumptions, maps
each one (secrets/config, volumes, service discovery, ingress/TLS,
health checks, network policies, the Docker-socket flow executor,
observability, image overrides, migrations) to candidate Kubernetes
equivalents, and proposes an incremental, docs-first path with open
questions, security/operational considerations, and a test/validation
strategy. The hardest item -- the Docker-socket worker executor -- is
laid out as candidate options without choosing one, and keeps flow
lifecycle explicit and inspectable per the #268 review lesson.
Refs #324
- Drop the hard-coded provider count to avoid doc drift as providers are
added; list the current provider types instead.
- Use the ADC-specific command (gcloud auth application-default login)
rather than the ambiguous 'gcloud login'.
- Reference the enum-swap migration pattern generically under
backend/migrations/sql/ instead of a single timestamped filename that
may be renamed or squashed.
Issue #321 requests a native Vertex AI provider with service-account /
ADC auth, opened after #310 clarified Vertex is not supported today. The
issue carries a full implementation outline and four open questions, and
the author asks for direction on adapter strategy and Gemini-vs-Claude
scope before implementing.
Add examples/proposals/vertex_ai_provider.md, a planning RFC that frames
the work before any code is written:
- Distinguishes the current options (AI Studio gemini, direct Anthropic,
AWS Bedrock, and the custom OpenAI-compatible LiteLLM proxy workaround)
from the proposed native vertex provider.
- Recommends a staged approach: v1 Gemini-on-Vertex with ADC /
service-account auth; Claude-on-Vertex deferred to a maintainer
decision, noting it likely belongs on the Anthropic adapter (Vertex
auth/endpoint mode) rather than the Gemini-shaped path because the
message schema differs.
- Models auth on the existing Bedrock multi-auth precedent (ADC default
chain plus service-account file), and flags that service-account JSON
is sensitive and must be file-mounted/secret-managed, never pasted into
UI or logs.
- Captures config/migration touch points (provider checklist, REST
Valid() whitelist, PROVIDER_TYPE enum-swap migration) so the eventual
implementation size is clear, and restates the issue's open questions.
Docs/RFC only. No code, schema, migration, generated, frontend, or
provider runtime files are touched, and no new env vars or types are
added; every VERTEX_* key and type named is labeled as a candidate. No
overlap with the provider files in open PR #328.
commitlint had no config anywhere (no config file, no husky commit-msg
hook), so its rules were never loaded; the "commit" script also pointed
at an uninstalled binary. Remove @commitlint/cli and
@commitlint/config-conventional, the dead "commit"/"commitlint" scripts,
and the stale commitlint entry in README Development Requirements.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Confirmed unused via depcheck + manual verification:
- anser, js-cookie, @types/js-cookie — no imports anywhere
- rehype-raw — only referenced in a vite manualChunks regex, never
imported as a markdown plugin (markdown.tsx uses rehype-highlight/slug
and remark-gfm); also dropped from that regex
- @graphql-codegen/{client-preset,near-operation-file-preset,typescript}
— codegen config uses explicit plugins (typescript-operations,
typed-document-node), not these presets/base plugin
Also drop the dead package.json "eslintConfig" block — it is ignored by
the flat config (eslint.config.mjs) and referenced an uninstalled
storybook plugin.
Verified: graphql:generate reproduces src/graphql/types.ts unchanged,
plus build, lint, 604 tests, and --frozen-lockfile all pass.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The plugin was a direct devDependency but never enabled in
eslint.config.mjs (0 active jsx-a11y rules via --print-config). Dropping
it removes dead weight and one stale eslint-9 peer constraint. Lint still
passes.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- add frontend/.nvmrc (24.17.0) as the single source of truth for Node;
GitHub CI reads it via node-version-file, Dockerfile uses node:24.17.0-slim
- bump packageManager to pnpm@11.8.0; drop "corepack prepare pnpm@latest"
so the pnpm version derives from packageManager everywhere
- migrate pnpm onlyBuiltDependencies -> allowBuilds in pnpm-workspace.yaml
(the package.json "pnpm" field is no longer read by pnpm 11)
- add a CI step that fails if the Dockerfile Node tag drifts from .nvmrc
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The directory expand/collapse control now shows the folder icon by
default and crossfades to a chevron on hover (motion, reduced-motion
aware); the single element toggles expansion on click. Nesting indent
gains the icon->text gap (22px/level) so a child's icon lines up under
its parent's label, and the header expand-all control moves to the
shared Button. Folder and chevron share the text-blue-400 accent set on
the parent (header chevron picks it up on hover).
Also prunes ~46 restatement/justification comments and a dead
collectAllFilePaths export (plus its tests) to match the house style.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Prettier / Lint / Test were `continue-on-error: true` (advisory — failures did not fail CI), the same gap that let type errors pile up. Now Prettier, Lint, Type check and Test all block the lint-and-test job (which runs on every branch push).
Prerequisite: `prettier --write` on 5 pre-existing non-conformant files (pages/login.tsx, lib/report/report-pdf.tsx, 3 *.test.tsx) so the now-blocking Prettier check passes — pure formatting, no logic change. Install stays advisory (setup step); backend checks unchanged.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
vite build strips types and never type-checks, and the old build`s bare tsc (solution config, files:[]) checked nothing — so type errors reached main unnoticed (which is how 76 had accumulated). Now they fail fast everywhere.
- build: `tsc -b && vite build` — `pnpm build` (and the Docker image build, which runs `pnpm run build`) fails on any type error before bundling.
- add `typescript` script (`tsc -b`, checks both app + node project configs).
- ci.yml: blocking "Frontend - Type check" step in lint-and-test (runs on every branch push; docker-build only runs on main/tags).
Verified: a type error makes both `pnpm run typescript` and `pnpm build` exit non-zero (vite never runs); removing it restores a clean build.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The provider form had 23 errors rooted in Zod v4: `z.preprocess` gives an `unknown` input type, which @hookform/resolvers v5 surfaces as the form field-values type, mismatching `useForm<output>` and cascading to every Control<FieldValues> site.
- Replace `z.preprocess` with explicit helper schemas (proper input/output types) and use `useForm<FormInput, unknown, FormData>`; make the reusable field components generic `<T extends FieldValues>` (Control<T> + FieldPath<T>).
- Fetch `thinking` on the model-config fragment (regenerated types.ts; backend ModelConfig.thinking exists).
- Validate the provider `type` into the ProviderType enum via `z.nativeEnum(...).parse` at the GraphQL boundary instead of an `as` cast (the form intentionally uses watch() to keep disabled fields in the payload, so its values stay input-typed).
tsc: 23 → 0; the frontend now has zero TypeScript errors. 606 tests pass; eslint + prettier clean.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Hack-free fixes (no `as any`/`@ts-ignore`/`as unknown as`):
- tsconfig lib es2023 for Array.findLast; tighten DocumentTitle TitleResolver to ApolloTitleComponent (the broad ComponentType was masked by findLast returning any).
- NodeJS.Timeout → ReturnType<typeof setTimeout> in browser code; models import casing (./User → ./user).
- settings prompt/api-token forms: type against the real generated fragment types and the Zod input/output split (useForm<Input, ctx, Output>); generic FormTextareaItem<T>.
- data-table / detail-nav: noUncheckedIndexedAccess guards; React vs DOM KeyboardEvent disambiguation; drop invalid user-event delay option.
tsc: 76 → 23 (the remaining 23 are one settings-provider Zod/RHF cluster). 606 tests pass; eslint + prettier clean.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
TypeScript 6.0 deprecated `baseUrl` (removed in 7.0). The `@/*` alias resolves relative to each tsconfig without it, and Vite resolves `@` via its own resolve.alias, so baseUrl was vestigial. Dropping it removes the need for `ignoreDeprecations: "6.0"`, which editor-bundled TypeScript (5.x) flagged as an invalid value (TS5103).
Also drop the dead `@env`/`./env.ts` entry from tsconfig.node.json: the file does not exist and the alias is imported nowhere.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Replace the deprecated typescript-react-apollo codegen plugin (unmaintained for Apollo Client v4) with typed-document-node. All ~105 useXxxQuery/Mutation/Subscription call sites are rewritten to the generic useQuery/useMutation/useSubscription(XxxDocument, ...) form, with skipToken replacing skip + conditional-variables.
graphql-codegen.ts: plugins typescript-operations + typed-document-node; add scalars { Time: string } (was unknown); drop withHooks/apolloReact* options. tsconfig.app/node.json: ignoreDeprecations "6.0" for the baseUrl TS5101 deprecation. Regenerate src/graphql/types.ts.
Behavior-preserving: variables, fetchPolicy, error handling, and subscription onData/refetchQueries are unchanged.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The /knowledges list query fetches documents with `withContent: false` to save bandwidth, writing an empty `content` to the shared normalized KnowledgeDocument cache entity. That clobbered the full body loaded by the detail query, so opening a document by direct URL (or reload) showed an empty editor.
Add a `content` field merge policy so an empty incoming value never blanks out a body already loaded.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Rename a knowledge document via a dedicated mutation that rewrites only the
question in cmetadata — no re-embedding, no embedder required — mirroring the
flows renameFlow pattern instead of round-tripping the full document through
updateKnowledgeDocument.
Backend:
- renameKnowledgeDocument(id, question) mutation + resolver (admin/user split;
ownership enforced at GetUserDocument, like the update pair)
- metadata-only query UpdateKnowledgeDocumentMetadata (no migration)
- unit + edge tests: metadata-only, missing-doc error, non-owner rejection
Frontend:
- renameKnowledge provider method; wire list and detail inline-rename to it
- drop the content "Preview" column and request the list with withContent:false
so it no longer pulls full document bodies
Verified end to end against a local Docker backend (rename works; content and
embedding preserved) and against the remote backend (graceful failure where the
mutation is not yet deployed).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Replace 13 `any` usages with real shapes: ProviderTest / ProviderTestResults
for the test-mutation payload, Control<FieldValues> for the form control, and
inferred element types in the result maps. Collapse the two duplicated
3-level-nested error-formatting blocks into one recursive formatFormErrors
helper — validation error output is byte-identical (verified against the same
inputs).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
react-hooks v6 ships this rule, but it only carries signal once the React
Compiler is enabled; until then it flags every RHF watch() and useReactTable
as unactionable noise (12 hits). Turn it off project-wide and drop the
now-redundant inline disable in use-element-virtual-list.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The CJK-detection regexes embedded a literal U+3000 ideographic space inside
their character class, which ESLint flagged as no-irregular-whitespace (error).
Switch the fullwidth ranges to \u escapes ( -〿-) — identical
match behaviour (verified: Han / U+3000 / fullwidth match, ASCII does not), no
irregular whitespace in source.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
No consumer reads the returned `virtualizer` (data-table destructures only the
spacer / measure fields), and exposing the raw instance leaks the abstraction —
the same dead, over-broad return just removed from useElementVirtualList. Drop it.
Also correct a stale doc claim: react-virtual does have an `enabled` option (it
gates the scroll listeners), the hook just doesn't surface it — so the
conditional-mount guidance stands without the false "no enabled option" note.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The sheet rendered every filtered option (1797 on a busy flows list), so the
filter re-render and the DOM weight (~1800 nodes) made filtering jank. Above a
100-item threshold the listbox now virtualizes via a new element-scroll
useElementVirtualList hook (the inner-container analogue of useWindowVirtualList):
only the ~30-node visible window is mounted. Small lists — and JSDOM tests —
keep rendering in full.
Roving focus onto an off-screen option scrolls it into view and focuses it once
its row mounts (pendingFocusId), so arrows/Home/End and open-time focus on the
current item work across the virtualized window. Options carry aria-setsize /
aria-posinset so screen readers still see the full count and position.
Measured live (chrome-devtools, test.pentagi.net, 1797-flow sheet): DOM nodes
~1800 → ~32; typing INP 258ms → ~200ms. The remaining cost is the flow.tsx page
re-render when the controller's filtered list changes (debounce flush) — a
separate concern. Open / End / Home / typing focus all verified; full suite green.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Typing in the sheet's search lagged badly (INP ~600ms on a 1797-item list): the
input bound to the controller's searchQuery, whose state lives in the page-level
hook (flow.tsx), so every keystroke re-rendered the whole detail page AND rebuilt
all ~1800 option rows before the caret could echo — characters appeared in batches.
Mirror the input value in local sheet state (instant caret echo, re-renders only
the sheet) and push to the controller in a transition (filtering + prev/next stay
correct; the heavy re-render no longer blocks the keystroke). Memoize the option
rows so a keystroke that only changes the local mirror does not rebuild them.
Measured live (chrome-devtools, test.pentagi.net, 1797-flow sheet): typing INP
606ms -> 258ms; all characters land, focus stays on the input. The residual is the
DOM reconciliation when the filter changes — addressed next by virtualizing the list.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Focus was driven off `focusedId` through an effect, so a reconciliation-driven
change (the filter shrinking and re-pinning to the first survivor) also moved
DOM focus, yanking it off the search input mid-type. Two document.activeElement
guards (the second added in 5a7bdca) papered over the timing; the rAF re-check
only ever fired under JSDOM and was dead in real browsers — verified live.
Move focus imperatively only where the user navigates: opening the sheet now
uses Radix's onOpenAutoFocus (preventDefault + focus the current option, with no
rAF race against the focus trap), arrow keys focus synchronously in the key
handler, and render-phase reconciliation only updates the roving tabindex. Both
guards, the effect and the rAF are gone, and the previously-flaky focus-steal
test is deterministic (10/10 isolated).
Verified live (chrome-devtools, test.pentagi.net, 1797-flow sheet): open focuses
the current option, typing keeps focus on the input with no dropped chars, and
arrows / ArrowDown-from-input move focus.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The account page tracked a single `editing` section, so opening one editor
unmounted any other open form and silently discarded its unsaved input. Track
an open-section set instead: opening a section no longer closes the others, so
a half-typed draft survives switching between name, email and password.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The forced password-change screen reused the compact account-card footer, so it
rendered small right-aligned buttons that clashed with the full-width "Sign in"
CTA on the same login page. Add two orthogonal props: layout
('horizontal' default | 'vertical') drives footer direction and button width;
buttonSize ('default' default, mirroring Button) drives size. The forced screen
passes layout="vertical" (full-width stacked buttons, submit on top, matching the
login button language); the account cards pass buttonSize="sm" to stay compact.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
isModal (gated the Cancel button) and showSkip (gated the Skip button) were
redundant with the onCancel/onSkip callbacks they always paired with: every
call site that set a flag also passed the matching handler, and none passed a
handler while wanting the button hidden. Render each button from its callback's
presence instead. Removes two props and a name that misdescribed its job
(isModal gated a button, not a modal).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The first migration pass missed call sites where the path is nested inside a
helper rather than passed straight to navigate/to: detail-navigation getHref
helpers, mergeHrefWithSearchParams row-open handlers, the knowledge create
redirect, the flow report window.open targets (wiring up the unused
routes.flowReport builder), and the OAuth return_uri. All now build from routes.
Add routes.test.ts: every builder output is asserted to match the app.tsx route
pattern that serves it via matchPath, guarding URL<->pattern sync, plus exact
checks for query encoding and the login return-url guard.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Step 3 of the route-registry migration: every /login redirect and post-login landing
fallback builds from lib/routes instead of hardcoded strings.
- protected-route, axios 401/403 interceptor, user-provider (logout, session-expiry,
/login + public-route checks) -> routes.login(...) / routes.login()
- oauth-result error redirect -> routes.login()
- login-form / public-route / login page post-login fallback -> routes.newFlow
getReturnUrlParam now has a single in-app caller (the routes.login builder) plus the
logout suffix-override; dropped its now-unused imports from axios and protected-route.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Step 2 of the route-registry migration: the provider/prompt settings pages build their
navigate() targets from lib/routes instead of hardcoded strings.
- settings-providers: provider(id), newProvider({ id | type }), newProvider()
- settings-provider: routes.settings.providers (x5)
- settings-prompts: routes.settings.prompt(name)
- settings-prompt: routes.settings.prompts (x2)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Introduce lib/routes.ts as the single source of truth for client route paths, with typed
builders for parameterised routes (flow, provider, prompt, login return-url, ...). First
migration step covers the settings shell we own:
- app.tsx settings index/catch-all redirects -> routes.settings.account
- main-sidebar Settings/Profile links -> routes.settings.root / .account
- settings-layout menu items + the "Back to App" fallback -> routes.*
The rest (settings provider/prompt pages, auth redirects, main nav) migrate in follow-ups.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Account was added as the first settings sidebar item, but the index and catch-all
routes still redirected to /settings/providers, so the gear "Settings" link dropped
the user on the second item. Point both redirects at /settings/account.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
(displayName).charAt(0) returns the first UTF-16 unit, so a non-BMP first character
(emoji, rare CJK) rendered as a lone surrogate (�). Spread to iterate by code point.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The settings shell's only exit was a "Back to App" link hardcoded to /flows, so opening
Settings or Profile from anywhere dropped the user at the flows list on the way out.
- the Settings and Profile entry links pass the current path as location.state.from
- SettingsLayout captures it once on entry (surviving sub-tab navigation, which drops
state) and points "Back to App" there, falling back to /flows
- tests: SettingsLayout honors the origin / falls back / preserves it across sub-tabs;
MainSidebar's Settings and Profile links carry the origin
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The three account forms duplicated the getApiErrorCode + ERROR_BY_CODE lookup pattern
verbatim, and each carried a dead `AuthRequired` entry that the axios interceptor
already handles (hard redirect) before the form's catch can render it.
- add resolveApiErrorMessage(err, map, fallback) next to the axios error helpers
- email/name/password forms use it and drop the unreachable AuthRequired entry
- unit-test the helper's precedence (mapped code > server msg > fallback)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
A network blip or 5xx on an /info refresh — after an email/name change or on plain
navigation — wrongly cleared local auth and bounced the user to /login, even though the
session cookie was still valid (the axios interceptor already handles real 401/403).
- refreshAuthInfo and the navigation refresh now keep the current session on a transient
/info failure instead of clearing auth and redirecting to /login
- add patchUser so the email/name forms reflect the change immediately, dropping the
dependency on a successful /info round-trip for the visible field
- tests: UserProvider keeps the session on transient failure (refresh and navigation
paths); forms call patchUser with the new value
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
- settings-account: local accounts expose name/email/password; OAuth accounts hide
the password card and email editing, keep the name editable, and label the provider
(known label, raw fallback, then generic); renders nothing without a user
- name-change-form (previously untested): seeds the current name, submits the trimmed
value and refreshes auth, blocks an empty name, maps Users.NotFound to friendly copy
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
ChangeNameCurrentUser issued a bare UPDATE and ignored RowsAffected, so a stale
session for a deleted user got 200 — inconsistent with the email/password handlers
(which 404) and leaving the frontend's Users.NotFound mapping unreachable.
- check RowsAffected and return ErrUsersNotFound (404) when no row matched
- document the 404 in the swagger annotation
- add TestChangeNameCurrentUser (success, missing user, invalid name)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Address Copilot review on PR #350: note that default_backend selects a crawl backend and passive extractors such as jsfinder are not selectable there; model scope_decision as a decision plus reason in both the field list and the JSON example; add an illustrative scope_entries example and clarify when allowed_hosts applies.
Refs #336
Add examples/proposals/headless_crawler_integration.md, a docs-only RFC proposing an optional, tool-agnostic crawler / URL discovery capability for PentAGI agents. Candidate backends are katana, crawlergo, rad, and jsfinder, framed as candidates with no mandatory default. The RFC keeps dictionary fuzzing (ffuf/dirsearch) unchanged, defines structured discovery artifacts (URLs, forms, parameters, JavaScript endpoints, status codes, source page, depth, scope decision), and keeps crawler URL discovery separate from the BrowserOS MCP interactive browser backend.
Refs #336
The vmail validator rejected addresses the frontend's z.string().email() accepts
(uppercase, TLDs longer than 4 chars like .cloud), so users saw a confusing 400.
- relax the vmail regex to allow uppercase and TLDs of 2+ chars
- lowercase + trim the new address in ChangeEmailCurrentUser and in the form schema
so storage, the duplicate check, and login lookups stay case-stable
- validator + change-email tests for mixed case and long TLDs
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
- authLoginCallback matches users by email alone so an OAuth login links into an
existing (incl. local) account instead of 500-ing on users_mail_unique
- relink on a create-branch unique-violation race instead of returning 500
- issue the session with the linked account's actual role privileges
- clear the stale OAuth provider link when a user changes their email
- map the email-change unique-violation race to 409 instead of 500
- isUniqueViolation matches Postgres and SQLite case-insensitively
- tests for link/create/blocked/role-inheritance/race, email 409, provider reset
- update auth form test selectors after the form refactor
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The account page is already available to OAuth users, so drop the
local-only gate on the user-menu "Profile" item to match.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- Keep /settings/account available to OAuth users: drop the redirect and
the local-only sidebar gate. Show the auth provider (Google/GitHub) on
the summary badge, render the email read-only, and hide the password
card for OAuth accounts. Fix the `provide` -> `provider` typo in User.
- Add a "Display name" card + NameChangeForm (PUT /user/name) for all users.
- Make the email/password forms consistent: lead with Current Password,
unify placeholders ("Enter your ..."), drop the redundant Current Email
field, and size form buttons to match the "Change" buttons.
- Rename the user-menu item "My Profile" -> "Profile".
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- OAuth login callback now stores the provider (google/github) on the
user record and backfills it for pre-existing OAuth users on login,
so the UI can show which provider an account is linked to.
- Add PUT /user/name for any authenticated user (including OAuth): a
NameChange model + ChangeNameCurrentUser handler that lets users edit
their display name. Placed in a /user group without localUserRequired.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
monaco-terminal.tsx had no importers; drop it together with the now-unused
monaco-editor and @monaco-editor/react dependencies (~3 MB). The component is
preserved on branch feature/frontend-monaco-terminal for later work.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Stabilizes a flaky test ("does not yank focus onto a listbox option when
filteredItems shrinks"): the rAF that moves roving focus now re-checks
document.activeElement before calling focus(), so a focus bounce between
the effect's gate check and the next frame no longer steals focus.
Provisional: the race only reproduces under JSDOM focus simulation (not in
real browsers), so the proper fix likely belongs in the test layer — to be
revisited separately.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Replace the few remaining space-y-*/space-x-* utilities with flex + gap to
match the codebase convention (only the vendored calendar primitive used
them outside this set).
In calendar.tsx the naive space-y→gap conversion shifted the date grid 16px
right: the months flex container holds a zero-width nav wrapper (its prev/
next buttons are absolutely positioned), so gap-4 spaced the (empty) nav from
the month. Drop the gap on months; keep it on month (caption ↔ grid, both
real children).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Replace the "My Profile" modal with a dedicated /settings/account page in
the existing settings sidebar (first nav item, gated to local accounts —
OAuth users are redirected). Email and password are edited inline via a
read-view → form pattern with a summary card.
- Extract a reusable InputPassword control built on input-group; use it in
login and both account forms (consistent focus ring + invalid border).
- Add getApiErrorCode and a per-form code→message map so backend error
codes surface friendly copy (the prior mapping was dead — msg always won).
- Co-locate form tests next to their source files.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Two crashes seen in production, both reproduced on the live app:
- "Failed to fetch dynamically imported module": after a redeploy rotates the
hashed chunk filenames, an open tab imports a deleted one. The server answered a
missing /assets/* with 301 -> index.html (HTML for a JS module -> a MIME
failure); it now returns 404 + no-store. The client listens for Vite's
vite:preloadError and reloads once (debounced) to pull the current build. Hashed
assets are served immutable; index.html and SPA routes no-cache.
- "Failed to execute 'removeChild' ... not a child of this node": an external
agent (a browser extension or auto-translation) mutates the DOM React owns,
desyncing reconciliation. A root react-router errorElement catches this
commit-phase crash and self-heals with a debounced reload, instead of React
Router's dead default error screen. translate="no" opts the English-only UI out
of the one trigger it can prevent (browser translation); the errorElement covers
the rest regardless of source.
Verified by reproducing both on the live old build (missing-chunk 301->HTML;
extension/translation DOM mutation -> the exact removeChild crash) and confirming
the fixed build recovers from each. Adds chunk-reload + RouteErrorBoundary unit
tests and a static-serving integration test.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Commit the ZIP response status and headers lazily, on the first byte written, via a small zipStreamWriter. A build failure before any output now returns the normal structured error response instead of a committed 200 with a truncated body; mid-stream failures still abort. Also check the reader Close error in the helper test and cover the pre-stream failure path.
DownloadResource and DownloadFlowFile built the entire ZIP archive in a bytes.Buffer before sending it, so heap usage scaled with archive size and a few concurrent large-directory downloads could exhaust process memory.
Stream the archive straight to the response writer via a shared streamZipArchive helper; the existing ZipResources/ZipDirectory/ZipRelativePaths helpers already accept an io.Writer. Responses are now chunked (no Content-Length) and memory stays proportional to one file's copy buffer.
Lifts the inline useWindowVirtualizer wiring from a8c3fbc into a reusable
useWindowVirtualList hook plus dedicated VirtualizedTableBody / DataTableRow
/ PaddingRow components, mounted only past the row threshold so
non-virtualized tables pay no window/ResizeObserver listener cost.
Corrects two latent issues from the inline version:
- Scroll anchor moved from the table wrapper (above <thead>) to <tbody>,
removing a header-height offset in the virtualizer's coordinate math that
overscan was masking. Overscan dropped 10 -> 5.
- Rows forward the stable virtualizer.measureElement ref instead of a
per-row arrow recreated each render, so React no longer detaches and
re-measures every visible row on every render.
Hardening:
- data-index + measure ref bundled into one `measurement` prop so the
"both or neither" invariant lives in the type, not a comment.
- a11y: virtualized tables expose aria-rowcount and per-row aria-rowindex,
so assistive tech sees the true total instead of only the ~20 rows in the
DOM.
- Hook observes only document.body for above-anchor layout shifts; the
anchor's own resize can't move its top edge, so observing it was dead.
Tests cover threshold gating, the renderSubComponent opt-out, the aria-row
attributes, and that data-index survives the Radix asChild context-menu
wrapper (the live /flows path).
Verified in-browser on /flows (1116 rows): 16 rows in the DOM,
aria-rowcount 1117, correct recycling top -> middle -> bottom, context menu
intact, zero console errors.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- Use the package-path form for the tester utilities
(go run ./cmd/ctester, go run ./cmd/etester test) instead of shell
glob / single-file invocations, which are more portable and avoid the
multi-file compile pitfall.
- Add -verbose to the container etester example so it matches the local
example.
- Wrap the new README Quick Start pointer across multiple lines; rendered
Markdown is unchanged.
- Drop the hard-coded provider count to avoid doc drift as providers are
added; list the current provider types instead.
- Use the ADC-specific command (gcloud auth application-default login)
rather than the ambiguous 'gcloud login'.
- Reference the enum-swap migration pattern generically under
backend/migrations/sql/ instead of a single timestamped filename that
may be renamed or squashed.
Issue #321 requests a native Vertex AI provider with service-account /
ADC auth, opened after #310 clarified Vertex is not supported today. The
issue carries a full implementation outline and four open questions, and
the author asks for direction on adapter strategy and Gemini-vs-Claude
scope before implementing.
Add examples/proposals/vertex_ai_provider.md, a planning RFC that frames
the work before any code is written:
- Distinguishes the current options (AI Studio gemini, direct Anthropic,
AWS Bedrock, and the custom OpenAI-compatible LiteLLM proxy workaround)
from the proposed native vertex provider.
- Recommends a staged approach: v1 Gemini-on-Vertex with ADC /
service-account auth; Claude-on-Vertex deferred to a maintainer
decision, noting it likely belongs on the Anthropic adapter (Vertex
auth/endpoint mode) rather than the Gemini-shaped path because the
message schema differs.
- Models auth on the existing Bedrock multi-auth precedent (ADC default
chain plus service-account file), and flags that service-account JSON
is sensitive and must be file-mounted/secret-managed, never pasted into
UI or logs.
- Captures config/migration touch points (provider checklist, REST
Valid() whitelist, PROVIDER_TYPE enum-swap migration) so the eventual
implementation size is clear, and restates the issue's open questions.
Docs/RFC only. No code, schema, migration, generated, frontend, or
provider runtime files are touched, and no new env vars or types are
added; every VERTEX_* key and type named is labeled as a candidate. No
overlap with the provider files in open PR #328.
Issue #313 reported flows that stall after a few steps when running a
custom OpenAI-compatible backend (LiteLLM in front of llama.cpp serving
qwen3.6-35b via LLM_SERVER_*). The backend returned malformed tool-call
arguments, surfaced as 'Failed to parse tool call arguments as JSON'
HTTP 500s and cascading retries. The maintainer fixed the stall in the
latest build by sanitizing wrong function-call arguments.
Add a troubleshooting subsection under Custom LLM Provider Configuration
that explains the root cause and how to diagnose it:
- Custom OpenAI-compatible backends must return valid tool-call
(function-call) JSON; llama.cpp, SGLang, and vLLM usually require a
specific tool-call parser and matching chat template, and not every
setup produces valid tool calls out of the box.
- Symptoms: 'Failed to parse tool call arguments as JSON', flow stalls,
looping tool calls, the 'failed to select primary docker image via
llm call' start-of-flow failure, and unexpected backend HTTP errors.
- Investigation: check PentAGI and backend/proxy logs, validate with the
ctester utility before a full flow, confirm the parser/chat template
match the model, and update PentAGI (recent builds sanitize malformed
function-call arguments).
Docs only. No tool-call parser code, provider runtime, schema, migration,
or config-default changes. Wording frames compatibility as dependent on
the backend's OpenAI-compatible tool-call behavior rather than claiming
every llama.cpp backend is supported.
Issue #61 asked for a proper guide on how to start using PentAGI. A
first-use guide (How to Use PentAGI After Login) already covers what to
do after login, but the maintainer kept the issue open until an article
about installing and configuring the product is published.
Add examples/guides/installation_configuration.md, a concise ordered
walkthrough that connects the existing detailed README sections into a
single path: choose installer vs manual Docker Compose, set core server
variables (PUBLIC_URL, CORS_ORIGINS, security vars), configure and test
an LLM provider with ctester, configure and test the embedding provider
with etester, optionally add search providers and the Graphiti/Langfuse/
observability stacks, then start and verify the stack and change the
default admin password. It ends with a quick checklist and links forward
to the existing post-login usage guide.
The guide links to the relevant README reference sections rather than
duplicating them. A single pointer link is added at the top of the
README Quick Start section for discoverability.
Docs only. No installer behavior, runtime code, env vars, or schema
changes. Every environment variable named in the guide already exists in
.env.example and backend/pkg/config/config.go.
Address review feedback on PR #325: capitalize SGLang to match the
project's name and clarify that tool calling and function calling
refer to the same capability.
Refs #309
Add a troubleshooting subsection to the Embedding Configuration and
Testing section for the common case where a flow starts but then waits
indefinitely with no subtasks progressing. As noted on the issue, this
is frequently caused by a misconfigured or unreachable embedding
provider rather than by the flow itself.
The subsection points users to "docker logs pentagi" as the first
check, to the etester "test" command to validate the embedding provider
and database connection without starting a flow, and to the specific
.env settings to verify (EMBEDDING_PROVIDER, EMBEDDING_MODEL,
EMBEDDING_URL, EMBEDDING_KEY, the LLM-provider fallback, PROXY_URL, and
HTTP_CLIENT_TIMEOUT). Documentation only: no new environment variables,
no provider default changes, and no code or test changes.
Refs #322
Add examples/proposals/kubernetes_deployment.md, an RFC-style design
surface responding to the Kubernetes deployment request in #324. The
document is docs-only: no Helm charts, manifests, operator, compose,
installer, or environment-variable changes, and it does not claim
Kubernetes is supported today.
It records the current Compose/installer deployment assumptions, maps
each one (secrets/config, volumes, service discovery, ingress/TLS,
health checks, network policies, the Docker-socket flow executor,
observability, image overrides, migrations) to candidate Kubernetes
equivalents, and proposes an incremental, docs-first path with open
questions, security/operational considerations, and a test/validation
strategy. The hardest item -- the Docker-socket worker executor -- is
laid out as candidate options without choosing one, and keeps flow
lifecycle explicit and inspectable per the #268 review lesson.
Refs #324
Add a troubleshooting subsection to the Docker Image Configuration
section explaining that "failed to select primary docker image via llm
call" (older versions: "failed to get primary docker image") is raised
when PentAGI's first LLM call fails during image selection, not when
Docker or the registry is unhealthy. Points users to PentAGI and LLM
backend logs, provider URL/key/model verification, and tool-call parser
configuration for custom/OpenAI-compatible/vLLM/sglang backends.
Remove/Purge/FactoryReset failed with "file does not exist" for stacks
that were never extracted (no docker-compose-*.yml). Now such stacks are
skipped instead of aborting the whole operation.
- Add composeFileExists check before destructive compose commands
- Add isDestructiveComposeOperation helper
Problem:
In the installer processor, post-operation state refresh failures from
checker.GatherUpdatesInfo were silently discarded, so apply/install/
update/remove/purge could report success even when the refresh failed.
Root cause:
Two distinct shadowing/fall-through patterns wrapped the error into a
variable that was never returned:
- In the deferred closures of applyChanges/install/update/purge, the
inner `if err := GatherUpdatesInfo(ctx); err != nil` shadowed the
named return `err`, so `err = fmt.Errorf(...)` assigned the shadow and
the wrap never reached the `sendCompletion(stack, err)` defer.
- In the ProductStackWorker cases of remove/purge, the block-local err
was wrapped but the case fell through without returning, while every
sibling check in the same switch returns on error.
Solution:
- Deferred closures: wrap into a `gatherErr` local and assign the named
return `err`, so the failure propagates to sendCompletion.
- Switch cases: `return` the wrapped error, matching the sibling checks.
Testing:
go build ./cmd/installer/... -> OK
go vet ./cmd/installer/processor/... -> OK
go test ./cmd/installer/processor/... -> ok
golangci-lint (ineffassign) on logic.go -> clean
Fixes#312
Root cause:
During flow creation the first LLM call selects the primary Docker
image. When the configured LLM backend is unsupported or returns 404,
prv.Call fails, but the wrapped error read "failed to get primary
docker image". Users repeatedly interpreted this as a Docker problem
(see #312, #309, #203) and debugged Docker instead of their LLM
provider configuration.
Solution:
Reword the wrapped error to "failed to select primary docker image
via llm call" so the LLM provider is identified as the failing
component while still mentioning the image selection step.
Testing:
go build ./pkg/providers/ -> OK
Added new test cases to validate containment barriers in the `ResolvePulledStagedTarget` and `ZipRelativePaths` functions, ensuring that paths escaping the designated directories are properly rejected. Updated the `knowledge_test.go` to include scenarios for handling nil embedder and error propagation during document creation, improving overall test coverage and robustness.
Enhanced the flowWorker's task processing by introducing a cancellable context for task execution. This change ensures that tasks can be properly cancelled without reporting false success states. The `runTask` method has been refactored to utilize a new `execTask` method, which centralizes task execution logic and maintains context integrity. This update improves flow control and error handling during task creation and execution.
Updated the Qwen agent configuration to include `extra_body` parameters for thinking control across various models. Added `enable_thinking` and `preserve_thinking` options for reasoning agents, while utility agents have `enable_thinking` set to false. Adjusted the Qwen client initialization to support these new configurations. Updated test report to reflect changes in success rates and latencies.
Adds an opt-in `isVirtualized` prop on DataTable, wired through
@tanstack/react-virtual's useWindowVirtualizer. Threshold gates short
tables (preserves Find-in-page, screen-reader enumeration). Padding <tr>
sentinels keep native HTML table semantics. Skipped when
`renderSubComponent` is set — expanded rows would need per-row
remeasurement we don't wire here.
Enabled on /flows. Measured with pageSize=All (1116 rows):
DOM elements: 41,657 → 1,121 (37x less)
tbody <tr>: 1,116 → 22
a11y tree size: ~485 KB → ~80 KB
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The old char-range regex missed hiragana, katakana, hangul, halfwidth
katakana and CJK Ext B+ ideographs, so Japanese/Korean reports would
not trigger NotoSansSC registration. Unicode property escapes cover
all CJK scripts and stay correct as Unicode adds new extensions.
Verified with 18 script samples (zh-Hans/Hant, ja kana, ko hangul/jamo,
fullwidth, CJK Ext B) — all pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Skips loading NotoSansSC.otf (8.1 MB) for reports without CJK chars.
Measured win on flow #50 download: 22.6 MB → 13.8 MB total traffic.
Adds `u` flag to CJK regexes so emoji surrogate pairs don't trigger
false positives (was matching U+D83D high surrogate on flow #41).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Stabilizes browser cache: changes in dashboard/knowledges/report code
no longer invalidate the heavy vendor libs. Side effect: the catch-all
(react|react-dom|react-router-dom) regex stopped swallowing
@monaco-editor/react and @tiptap/react, so react-vendor drops 469→178 KB.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Lint warnings 44 → 25. The remaining 14 `any` warnings sit in
settings-provider.tsx (provider config form + test results dialog,
needs domain knowledge — deferred per scope). The other 11 warnings
are React Compiler "Compilation Skipped" notices, not code issues.
- lib/log.ts: any → unknown (5) — logger accepts arbitrary input
- shared/markdown.tsx: typed the recursive ReactNode walker with a
`hasChildrenProp` type guard around `isValidElement`; the components
map now uses react-markdown's `Components` type so `code` / `pre`
overrides infer their props (5)
- settings-prompt.tsx: `ControllerProps.control: Control<FieldValues>`,
`field: ControllerRenderProps<…>`, validation result typed against
`ValidatePromptMutation['validatePrompt']`, dropped a stray
`as any` on `removeEventListener` options (4)
- settings-prompts.tsx: row sub-component params typed via
`Row<T>` from @tanstack/react-table (2)
- settings-providers.tsx: provider icon map typed against
`SVGProps<SVGSVGElement>`, row sub-component via `Row<Provider>`,
recursive `getFields(obj)` narrowed from `any` to `unknown` with a
single boundary cast for `Object.entries` (3)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Baseline 8/10 fail (80% flake) → 20/20 pass. Root cause was `user.type`
racing the Radix Sheet focus trap, not the `useDebounce` macrotask
theory from the prior investigation: with `defaultOpen=true` Radix sets
`body { pointer-events: none }`, swallowing user-event's internal click,
so keystrokes route to whatever element currently holds focus (the
SheetContent close button) instead of the input. `inputValue` stays
empty and the listbox never narrows.
`fireEvent.change` mirrors the sidestep already used in the
URL-filter AND test in the same file.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Followed up on the "no war-story comments" rule (memory file added a
few commits ago, then promptly broken in the X-button addition).
Pass through every comment with the test "remove it — does a senior
reading the code for the first time understand less?".
Removed:
- "Same two-cell shape as DataTableFilter, see its docstring" — cross-
file rationale belongs in commit history.
- "Hint shown over the collapsed trigger. Kbd self-themes…" — Kbd
configuration detail, not part of this component's contract.
- "Mirror size='sm' button geometry used by HeaderButton" — micro
implementation detail.
- "Collapsed trigger sits flush… has-[>button]:ml-[-0.45rem] handles
the analogous adjustment" — CSS quirk story.
- "The trigger is a real <button> — never a <div> with onClick" —
generic HTML/a11y factoid, not specific to this file.
- "The component is controlled — parent owns searchQuery" — visible
from the props shape.
- "Belt-and-braces for programmatic clears" — defensive-style war
language, replaced with one line stating the effect's purpose.
- "Initialise expanded if the parent already has a non-empty query" —
duplicates `useState(() => searchQuery.trim().length > 0)`.
Kept (in single-line / sub-3-line form):
- `COMMIT_DEBOUNCE_MS` shares timing with DataTableFilter.
- `External → local sync` effect intent.
- `rAF` before focus so motion's transform has started.
- `handleInputBlur` reads `localValue`, not the prop (subtle invariant).
- Auto-collapse effect purpose.
- `inputRef.current?.focus()` in `handleClear` (otherwise auto-collapse
fires and the field disappears under the user).
- Top-level JSDoc shrunk from 28 lines to 5 — what it does plus the
two equivalent clear paths.
Behaviour unchanged. 15/15 tests still pass, lint clean. File: 340 → 260
lines (-24%).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
`DataTableFilter` already ships a conditional trailing `<X>` clear
button; `InputSearch` (the collapsible variant used for /knowledges
semantic search and the same shape sitting in flow detail searches)
only offered keyboard Esc to clear. Unify so every search field across
the app has the same shape.
Implementation:
- Extract a shared `handleClear` used by both the new X button and the
first-Esc branch. The path cancels any pending debounce, emits `''`
upstream, and explicitly returns focus to the input — this matches
the Esc-clear path (where focus is already on the input) and
side-steps the programmatic-clear collapse effect, so the field
stays open and ready for fresh typing.
- Render the X only while `isExpanded && localValue` so it can never
appear on a collapsed/empty field. `aria-label` is contextual:
"Clear search knowledge documents" / "Clear semantic search" / etc.,
derived from the host page's `ariaLabel`.
- Update the JSDoc to describe both clear entry points.
Tests (input-search.test.tsx, 15 total — 10 baseline + 5 new):
- absent on empty mount
- present on deep-linked non-empty mount
- shows/hides as the user types and clears
- click clears value, emits `''` upstream, keeps focus on input,
prevents the trigger from re-appearing
- click mid-typing drops any pending debounce — no leaked emit
Browser verified on /knowledges semantic search:
beforeClear { value: 'jwt', url: '?qs=jwt', xPresent: true }
afterClear { value: '', url: '', xPresent: false, focusOnInput: true }
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
After the `chore(frontend): upgrade graphql-codegen toolchain` upgrade
(8a3d4e9) the generated `src/graphql/types.ts` carried every base type
twice — once as `export enum Foo` (from `typescript`) and once as
`export type Foo = 'a' | 'b'` (from `typescript-operations`). Vite's
dependency scan failed on the duplicate declarations with 29
`Identifier 'X' has already been declared` parse errors, which made
the dev server occasionally die on cold start.
Root cause: this was a stale v5-style config running on v6 plugins.
The v6 migration guide is explicit — `preResolveTypes` has been
removed, and `typescript-operations@6` now emits base types itself,
so the canonical setup is `plugins: ['typescript-operations']` rather
than `['typescript', 'typescript-operations']`. Keeping both meant the
two plugins independently emitted the full type set in different
shapes.
Bisect confirmed the split: `typescript` alone → 1327 lines, no
duplicates; `typescript-operations` alone → 1311 lines, no
duplicates; the pair → 2639 lines with 29 duplicate type names.
With `typescript-react-apollo` also in the mix the regenerated file
ballooned to 8819 lines, half of which was the shadow set.
Fix:
- Drop the `typescript` plugin from the codegen config.
- Drop `preResolveTypes: true` (removed in v6).
- Add `enumType: 'native'` so the call sites that use enum-style
access (`KnowledgeDocType.Answer`, `AgentConfigType.Adviser`, …)
keep compiling — without it, v6 defaults to string-literal unions.
Result:
- `src/graphql/types.ts` shrinks 8819 → 7586 lines, zero duplicate
declarations.
- `KnowledgeDocType`, `AgentConfigType`, etc. remain real TS `enum`s
so `KnowledgeDocType.Answer`-style access keeps working.
- `pnpm run build` clean, lint clean, 531/531 tests passing.
- Vite dev start no longer prints `[PARSE_ERROR] Identifier X has
already been declared`. `/knowledges` (the page that exercises
enum access) loads with 10 rows and zero console errors.
Migration guide:
https://the-guild.dev/graphql/codegen/docs/migration/operations-and-client-preset-from-5-0
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Reviewing 17451e7: the dedupe was added in reaction to a runtime
`Cannot read properties of null (reading 'useRef')` that I attributed
to dual React copies via pnpm hoist. But I applied two changes at
once — clearing `node_modules/.vite` and adding dedupe — and never
isolated which one actually fixed it.
Empirical re-check just now: production build, dev server, and
the affected page all work with dedupe removed. The real cause was
the stale Vite pre-bundle (`.vite/deps/`), which doesn't auto-rebuild
after `pnpm add` in a running dev server. Cache clear alone fixes it.
That makes the dedupe defensive hygiene at best, and the 7-line
war-story comment alongside it actively misleads — it pins a problem
on a mechanism that wasn't the cause. Removing both keeps the config
honest. QA report updated to record the misdiagnosis as a process
note instead of an architectural rule.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Run `pnpm prettier:fix` brought three files into compliance:
- data-table.test.tsx — new race-scenario suite added in the previous
commit; prettier preferred a slightly different multi-line shape for a
couple of `render(<FilterHost />)` calls.
- input-search.test.tsx — new file in the previous commit; same minor
multi-line reshaping for `render(<SearchHost />)`.
- settings-api-tokens.tsx — pre-existing single-line nested ternary that
predates this branch, now collapsed to one line per prettier.
No behavior change. Format-only.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
After landing the imperative-timer fix and extracting `useDebouncedCallback`
into our own hook, the use-site count climbed past three and the case for
a single, battle-tested contract beat the case for in-tree code. Drops
both our `useDebouncedValue` and `useDebouncedCallback` and routes every
caller through `use-debounce@10.1.1` (1M+ weekly, ~3KB gzip).
API mapping at each use-site:
- value debounce: `useDebouncedValue(v, ms)` → `const [v] = useDebounce(v, ms)`
- callback debounce: `useDebouncedCallback(fn, ms)` → identical signature,
same `.cancel()`/`.isPending()` semantics we relied on, plus `.flush()`
and leading/trailing/maxWait options we now get for free.
Files touched (7 use-sites): data-table.tsx, input-search.tsx,
use-table-state.ts, use-table-query-filter.ts, knowledges-provider.tsx,
use-flow-files-search.ts, use-detail-navigation.ts.
pnpm + Vite gotcha: pnpm hoists into `.pnpm/<name>@<ver>/`, so any
transitive `import React from 'react'` from a third-party package can
resolve to its own physical copy. With one path through our code and
another through use-debounce, the runtime crashed at `useRef` with
"Cannot read properties of null (reading 'useRef')". Added
`resolve.dedupe: ['react', 'react-dom']` in vite.config.ts so the
bundle ships exactly one React.
Tests:
- new input-search.test.tsx (10 tests) covers collapsed/expanded
presentation, expand-on-click + rAF focus, burst-typing coalesce,
Esc-clear mid-debounce, two-stage Esc semantics, external-source-wins
race, Ctrl+F / Cmd+F global hotkey expansion.
- data-table.test.tsx +5 tests: deep-link initial filterValue,
6-keystroke burst coalesce, unmount-mid-debounce cleanup, two
independent DataTables on one page (settings/prompts shape),
back-button-style external clear, three-round type/clear stress.
- full suite: 541/541 passing, lint 0 errors.
Manual smoke via Chrome DevTools MCP on every page that mounts a
filter input — /flows, /templates, /settings/api-tokens,
/settings/prompts (both tables independent), /knowledges (filter
+ semantic search hitting the server through ?qs=). All scenarios
collapse to a single `[{v="", u=""}]` transition; no URL re-emit
after X, no leftover timer after Esc, no cross-table leakage.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The previous iteration moved DataTableFilter / InputSearch off
`useDebouncedValue` and onto an inline `setTimeout` + `pendingTimerRef`
+ `cancelPendingEmit` dance. That fixed all four race scenarios but
left imperative scheduling living inside components — a code smell
flagged in review. After surveying the React 19.2 surface area
(`useDeferredValue` is for *render* priority, not side-effect throttling;
`useTransition` doesn't apply to controlled inputs; `useEffectEvent` is
restricted to handlers called from within Effects) and `use-debounce`'s
API, the right shape is a small, dependency-free hook.
`useDebouncedCallback(fn, delayMs)` returns a stable callable with
`.cancel()` / `.isPending()`. Timer state lives in a closure variable
inside a `useState` lazy initialiser, so:
- the returned identity never changes (safe in effect deps and memoised
children);
- there are no refs to read during render (no React Compiler complaints);
- `fn` and `delayMs` go through `useLatestRef` so the dispatched call
always sees the freshest closure — inline arrows in parents are free.
DataTableFilter / InputSearch shrink to one useState + one useRef
(`lastEmittedReference` distinguishes our own router round-trip from a
true external change) + one useEffect (external sync). All four
regression tests added in the previous commit still pass; five new unit
tests pin `useDebouncedCallback` semantics (burst coalescing, cancel,
isPending, latest-closure read, unmount cleanup). Browser repro on
/flows for both X-after-flush and X-before-flush scenarios: a single
transition `v="" u=""`, no resurrection.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Previously DataTableFilter (and InputSearch) layered four cells holding
the same logical value — `localValue` (sync useState), `debouncedValue`
(async useState inside `useDebouncedValue`), `lastEmittedReference`
(ref), and the parent's `query` prop (async round-trip) — and stitched
them together with two opposing useEffect's. The async `debouncedValue`
cell could be read out of phase from any other effect, which leaked
through as four distinct races: X clear after debounce flush (URL/state
snap back ~50–80 ms), X clear *before* debounce flush (pending timer
fires after clear), external `query` change mid-debounce (pending
typed value clobbers external), and tail-end character loss on fast
typing across the round-trip boundary.
Drop the extra storage cell. The debounce is now an imperative
`pendingTimerReference` mutated only by `handleChange`,
`cancelPendingEmit`, and the external-sync effect. All outbound
emission goes through one `emit(next)` function that synchronously
cancels any pending timer before sending. `handleClear` → `emit('')`.
External `query` change → cancel pending + accept. Unmount → cancel.
`onQueryChange` lives behind `useLatestRef` so effect deps stay
stable across parent re-renders.
Four regression tests in data-table.test.tsx pin all four scenarios.
Verified by rolling back the fix temporarily — the X-clear race test
fails with the exact `emitted = ['', 'alpha', '']` from the original
browser repro. With the fix in place all four pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
DataTableFilter / InputSearch listed `onQueryChange` (an inline arrow from
the parent — fresh reference per render) in the emit effect's deps. After
the X-clear handler set `lastEmitted=''` and propagated upstream, the
parent re-rendered and handed back a new handler reference, re-running
the effect while `debouncedValue` was still the pre-clear value
(`useState` inside `useDebouncedValue` hadn't yet been updated by its
trailing `setTimeout`). The effect saw `debouncedValue='alpha' !==
lastEmitted=''` and re-emitted `'alpha'`, snapping URL/state back for
~50–80 ms. JSDOM regression captured `emitted = ['', 'alpha', '']`.
Stash the handler in `useLatestRef` and drop it from deps so the effect
fires only when the observed value actually changes. Same fix in
InputSearch's Esc-clear path. New test in data-table.test.tsx pins the
behavior — fails with the previous code (`['', 'alpha', '']`), passes
now (`['', '']`).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Issue #310 asks how to provide a Google Vertex AI API key in .env for
Anthropic Claude. PentAGI currently has no dedicated Vertex AI provider
path in code: backend/pkg/config and backend/cmd/installer do not read
VERTEX_API_KEY, GOOGLE_APPLICATION_CREDENTIALS, or any vertex_ai
variable. The supported routes for Claude today are direct Anthropic
(ANTHROPIC_API_KEY / ANTHROPIC_SERVER_URL) and AWS Bedrock (BEDROCK_*).
Document this explicitly so users do not assume a hidden Vertex AI
configuration path exists:
- README.md: add a NOTE callout inside the Anthropic Provider
Configuration section listing the supported routes and pointing
users who need Vertex AI today at the OpenAI-compatible custom LLM
provider path (LLM_SERVER_URL / LLM_SERVER_KEY / LLM_SERVER_MODEL)
fronted by a translating gateway, with a caveat that reliability
depends on the gateway.
- backend/docs/config.md: add a matching Note paragraph under the
Anthropic section that points at the AWS Bedrock and custom LLM
provider sections, and states that no VERTEX_API_KEY or
GOOGLE_APPLICATION_CREDENTIALS variable is wired into provider
initialization today.
Docs-only change. No runtime Go code, no installer behavior, no
generated files, no new environment variables. All env var names cited
in the new text already exist in the current PentAGI .env.example,
backend/pkg/config, and backend/cmd/installer.
DeepSeek V4 thinking mode defaults to enabled on both deepseek-v4-flash
and deepseek-v4-pro; non-thinking behavior requires an explicit toggle.
Per official docs, in thinking mode temperature/top_p/presence_penalty/
frequency_penalty are ignored, so the existing Flash role sampling knobs
would have been silently no-ops without the toggle.
Add extra_body.thinking.type=disabled to the five non-thinking Flash
roles so deepseek-v4-flash actually runs in non-thinking mode and
honors the role's temperature/top_p settings:
- simple, simple_json, adviser, searcher, enricher
Pro roles (primary_agent, assistant, generator, refiner, reflector,
coder, installer, pentester) intentionally keep thinking enabled (the
V4 default) for reasoning, tool-use, and security analysis.
PentAGI provider config already supports extra_body as a first-class
yaml field on AgentConfig and forwards it through openai.WithExtraBody,
which the vxcontrol langchaingo fork serializes at the top level of the
Chat Completions request - the same pattern Kimi uses for tool_choice.
No code, schema, or LiteLLM prefix changes required.
Touches:
- backend/pkg/providers/deepseek/config.yml (embedded production config)
- examples/configs/deepseek.provider.yml (user-facing example)
No change to role-to-model mapping, model metadata, pricing, README
wording, LiteLLM prefix, unrelated providers, lifecycle, queues, or
installer flow.
- Update model descriptions to reflect V4 1M context window (up to 384K output)
instead of legacy 128K wording in models.yml and README.
- Split Flash and Pro pricing per official DeepSeek API docs:
- deepseek-v4-flash: input 0.14 / output 0.28 / cache_hit 0.0028 per 1M tokens
- deepseek-v4-pro: input 0.435 / output 0.87 / cache_hit 0.003625 per 1M tokens
- Apply per-role price split across all 13 role configs in both the embedded
config.yml and the user-facing examples/configs/deepseek.provider.yml.
- Replace stale "cache pricing is 10% of input cost" claim in the README,
which no longer holds for either V4 model.
- No change to LiteLLM prefix behavior, role-to-model mapping, lifecycle,
queues, GraphQL schema, migrations, frontend, or installer flow.
- README: align supported-models intro with the local convention used
by every other provider section ("Models marked with `*` are used
in default configuration"), so the asterisk on each model ID has a
near-by explanation.
- Installer help (`LLMFormDeepSeekHelp`): swap the legacy
"DeepSeek-Chat" / "DeepSeek-Reasoner" bullets in "Default PentAGI
Models" for the current `deepseek-v4-flash` / `deepseek-v4-pro`
defaults so the wizard guidance matches the bundled config.
No code, schema, or LiteLLM prefix behavior changes.
The JSDoc blocks added in afb9b63 mostly paraphrased the 12 lines of
code below them. Reviewing line-by-line:
- "two axes" / "filter active vs no filter" / per-state copy — code
reads identically and is right next to the comment.
- "kept inline because tightly coupled to effectiveQuery" — every
helper in this file is inline, that's the existing convention.
- "colSpan={columns.length} parent" — the one call site is 10 lines
below in the same file.
- "for callers that have not migrated yet" — `empty?:` being optional
already says this.
- "so existing tests stay green" — the test itself documents the
contract; deleting the fallback fails it loudly.
Kept the one piece TypeScript can't express: a single-line hint that
`entityName` wants the plural lowercase form so the generated copy
reads naturally mid-sentence. That shows up in IDE autocomplete and
saves a "Flows" → "No Flows match" first-try mistake.
No behaviour change. 28/28 DataTable tests pass, 0 ESLint errors.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Resolves QA report observation O9. Every list page used to render the
bare "No results." label when its DataTable had no rows — both for a
truly empty dataset and when a filter narrowed the result set to zero.
The Resources page already had a better pattern (shadcn <Empty> block
with a filter-aware copy that cited the query), so propagate it to the
shared DataTable.
API
- New optional `empty?: { entityName?: string }` prop on `DataTable`.
- When `entityName` is provided, the body cell renders an `<Empty>`
block:
filter active → Search icon + "No matches" + "No <entity> match
<code>{query}</code>. Try a different query."
no filter → Inbox icon + "No <entity> yet"
and the pagination footer mirrors the entity name ("No <entity>"
instead of "No results").
- When `entityName` is omitted, the existing bare "No results." cell
and "No results" footer are kept verbatim — preserves backward-compat
for call sites that have not migrated and for the existing test that
asserts the legacy copy.
Per-page wiring
Plural lowercase names match how a screen reader reads them mid-
sentence:
flows → "flows"
templates → "templates"
knowledges → "knowledge documents"
/settings/providers → "providers"
/settings/api-tokens → "API tokens"
/settings/prompts ×2 → "agent prompts" / "tool prompts"
Tests
- Existing `'No results.'` assertion stays valid: it renders a
DataTable without the `empty` prop, exercising the legacy fallback
path.
- Added 3 new cases under `DataTable — empty results`:
1. legacy fallback when `empty.entityName` is omitted
2. data-empty "No <entity> yet" when no filter is active
3. filter-empty "No <entity> match <query>. Try a different
query." with the query cited verbatim
Verified
- 0 ESLint errors, 44 pre-existing warnings.
- 511/511 vitest pass in sequential mode and when the affected files
run isolated. A pre-existing concurrency flake in
`detail-navigation-sheet.test.tsx` (`typing narrows the listbox
immediately when searchDebounceMs=0`) occasionally surfaces under
vitest's default `--file-parallelism` — unrelated to this change,
passes deterministically with `--no-file-parallelism` and when the
file is run in isolation.
- Browser sweep across 7 tables (`/flows`, `/templates`,
`/knowledges`, `/settings/{providers,api-tokens,prompts(×2)}`) all
render the new copy with `?q=ZZZZZZ`.
References
- shadcn `Empty` component (already vendored in
`components/ui/empty.tsx`)
- shadcn.io `tables-empty` block FAQ (best-practice: distinguish
filter-empty vs data-empty via `hasActiveFilters` boolean, ground
the empty cell in a Lucide icon, surface a "next-step" hint).
- Existing precedent in `pages/resources/resources.tsx` —
`No resources match <code>{q}</code>. Try a different query.`
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Reverts the O10 part of commit 04702c3. The original change renamed
the provider clone URL parameter from `?id=` to `?clone=`. On second
look the rename solved no real problem:
- No security issue: PentAGI is a single-tenant local admin tool, so
there is no cross-tenant info leak from a shared URL.
- No bug: the form behaviour was identical before and after.
- No UX impact: the URL is generated by the "Clone" action, not typed
by users; the bare `?id=` is also explicit enough in context
(settings-provider.tsx gates it on `isNew`, so the meaning is
"source provider to clone from").
What the rename did cost: it broke backward compatibility with any
bookmarks/links saved in `?id=` form. Restore `?id=` to remove the
needless churn.
The rest of commit 04702c3 (O7 dialog case, O8 "API Tokens" unify,
O11 button label + JSDoc, O12 italic placeholder) addressed real
inconsistencies and stays in place.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Resolves QA report observations O7, O8, O10, O11, O12.
O7 — Confirm dialog title case
The Resources page rendered "Delete Directory" / "Delete Resource" in
Title Case while every other delete confirm (template, knowledge,
token) used Sentence case ("Delete template", "Delete token"). Aligned
the resources copy to "Delete directory" / "Delete resource".
O8 — /settings/api-tokens identity mismatch
Three names referred to the same page:
- sidebar link / h1: "PentAGI API"
- tab title (route registry): "API tokens"
- menuItems entry: "PentAGI API"
Unified everything to "API Tokens". Also removed the now-redundant
api-tokens special case in settings-layout's SettingsHeader (it always
returned the same value the menuItems lookup would have produced).
O10 — Provider Clone URL parameter
`/settings/providers/new?id=5` collided semantically with the rest of
the codebase, where `?id=` usually means "this is the record being
edited". Renamed to `?clone=5` so the intent is explicit when the URL
is shared or shows up in logs. Updated the reader in
settings-provider.tsx (`formQueryParams.id` → `formQueryParams.clone`)
to match.
O11 — "Create Provider" button accessibility
The button is a DropdownMenuTrigger that opens a provider-type chooser
before navigating to /new — not a submit button. Sighted users get
this from `<ChevronDown />` and Radix's `aria-haspopup="menu"`, but
the bare visible text "Create Provider" reads as a confirmation
action to screen readers. Added `aria-label="Create provider — choose
type"` and a block comment explaining the pattern so future
maintainers don't try to "fix" the dropdown into a direct submit.
O12 — `(unnamed)` placeholder rendering
Tokens with empty name rendered as literal `(unnamed)` with
text-muted-foreground only. Added `font-normal italic` so the
placeholder reads as missing data rather than a real name (the column
otherwise uses font-medium).
Verified: 0 ESLint errors, 508/508 tests pass.
Browser regression sweep across 9 pages (/dashboard, /flows,
/templates, /knowledges, /resources, /flows/:id, /settings/{providers,
api-tokens,prompts}) still returns 0 icon-only buttons without an
accessible name.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The DeepSeek provider config still defaulted to the legacy
`deepseek-chat` and `deepseek-reasoner` model names, which the
upstream DeepSeek API has announced for deprecation on 2026-07-24.
A first-run install therefore breaks once the legacy names are
removed.
Swap the defaults to the current DeepSeek V4 family:
- non-thinking roles use `deepseek-v4-flash`
- reasoning-heavy roles use `deepseek-v4-pro`
The change is limited to the embedded `config.yml` / `models.yml`
inside `backend/pkg/providers/deepseek`, the matching example at
`examples/configs/deepseek.provider.yml`, the `DeepSeekAgentModel`
fallback constant in `deepseek.go`, and three doc references
(README.md, backend/docs/config.md, backend/docs/llms_how_to.md)
plus one installer help string in
`backend/cmd/installer/wizard/locale/locale.go`. LiteLLM prefix
behavior is untouched.
Resolves QA report BUG #16 and BUG #17.
BUG #16 — /settings/prompts/<invalid> tab title fallback
formatPromptId() blindly capitalized whatever the URL passed in, so a
nonexistent id like /settings/prompts/99999 produced the tab title
"99999 — PentAGI" (and an "Edit Prompt" header with a literal "99999"
in the error message). Valid prompt ids are camelCase identifiers
(e.g. "agentSelector"). Reject anything that does not match
/^[a-z][a-zA-Z]*$/ and fall back to a generic "Prompt", so the title
becomes "Prompt — PentAGI" for invalid ids; valid ids keep their
existing "Agent Selector — PentAGI" rendering.
BUG #17 — Chrome DevTools "form field needs id/name" + label-for
Two separate issues on /flows and /flows/🆔
1) Four hidden <input type="file"> elements driven programmatically
by use-resources-upload / use-flow-files-upload / flow-form lacked
`name`. Added descriptive names (`resource-upload`, `flow-file-upload`,
`flow-form-attachment`) plus `aria-hidden="true"` and `tabIndex={-1}`
— these inputs are never user-focused (the button triggers .click()
via a ref), so excluding them from the accessibility tree is correct.
2) <FormControl><Switch/></FormControl> + <FormLabel> for the "Use Agents"
field on the assistant flow form was rendered without a wrapping
<FormItem>, so useFormField() read the default empty context and
formItemId became "undefined-form-item". Chrome then flagged "label
for=undefined-form-item" as an orphan. Wrapped the cluster in
<FormItem className="flex flex-row items-center gap-0"> so useId()
generates a real id and the label binds to the Switch trigger
button correctly.
Verified: 0 ESLint errors, 508/508 tests pass.
On /flows the page now has 0 form fields without id/name.
On /flows/:id the only remaining unlabeled fields are third-party
internals we do not own (xterm.js helper textarea, Radix Switch
primitive checkbox, react-textarea-autosize ghost) — Chrome's count
dropped accordingly.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Page-level row-action triggers were split between two conventions:
- 4 pages used <span className="sr-only">Open menu</span> inside <Button>
- 3 pages (touched in commit 9eee2b4) followed the same pattern for consistency
Project has no i18n pipeline that benefits from sr-only text-node
translation, and the rest of the codebase already uses aria-label for
icon-only buttons (pagination, forms, theme tabs, toggles). Unify all
6 page-level row-action triggers to aria-label="Open menu":
- pages/flows/flows.tsx
- pages/knowledges/knowledges.tsx
- pages/templates/templates.tsx
- pages/settings/settings-providers.tsx
- pages/settings/settings-prompts.tsx (×2 — agent + tool tables)
- pages/settings/settings-api-tokens.tsx
shadcn UI library components (sheet, dialog, sidebar, breadcrumb) keep
their sr-only spans untouched — that is upstream shadcn convention and
not in scope here.
Verified: 0 ESLint errors, 508/508 tests pass, browser sweep across
6 list pages confirms aria-label="Open menu" rendered correctly and
no icon-only buttons remain without an accessible name.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The clamping effect compared the URL to a `safePageIndex` derived from the
internal mirror. After popstate the URL refreshes one render before the
mirror catches up; after a page-size change the mirror refreshes one
render before the URL — so each side echoed the stale source back over
the fresh one, oscillating `/flows` ↔ `/flows?page=2` indefinitely.
Now clamping only fires when both URL and mirror agree out-of-range, and
goes through a new `setPage(idx, { replace: true })` opt-in so a typed
`?page=999` no longer leaves a history entry the next back-press would
re-trigger.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Radix ScrollArea wraps children in a display:table viewport that grows
to intrinsic content, so renderItem rows with white-space:nowrap text
pushed each option past the sheet's right edge. Swap to plain
overflow-y-auto and add min-w-0 to the flex chain so truncate finally
takes effect on long flow / template / knowledge titles.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Strip section banners, "Helper function to X" labels above self-describing
identifiers, "GraphQL query/mutation/subscription" markers, and the
copy-pasted `// Create debounced function` / `// Filter by search` blocks
that lined every flow feature. Where a comment hid a non-obvious reason
(history blocker pattern, watch() vs getValues(), CJK font fallbacks),
rewrite it as a WHY comment instead of dropping it.
Net diff: -571/+78 across 57 files. Lint clean (pre-existing `any`
warnings unchanged), `tsc` errors unchanged, 506/506 tests still pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Terser strips the inner function-expression name in `apolloTitle()` during
the production build, leaving an anonymous `function({params})` whose
`fn.name === ''`. The old PascalCase heuristic in `DocumentTitle` then
misclassified the component as a `(params) => string` resolver, called it
with raw `match.params`, and crashed `variables({flowId})` with
"Cannot destructure property 'flowId' of undefined" on every /flows/:id
view in production.
Attach an explicit `Symbol.for('pentagi.apolloTitle')` marker via
`Object.assign` in the factory and expose `isApolloTitle()` as the only
public guard. Symbol-keyed properties survive Terser regardless of
`mangle.properties` settings, and `Symbol.for` keeps the marker stable
across accidental double-bundles (workers, SSR boundaries). The
`document-title` consumer now imports the guard, not the symbol, so the
marker stays an implementation detail of the apollo-title module.
Cover the regression with a dedicated `apollo-title.test.tsx` that
simulates name stripping via `Object.defineProperty(fn, 'name', { value: '' })`
and asserts the guard still recognizes the component.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
HTML's default `type` for a `<button>` inside a `<form>` is `submit`,
so every Button without an explicit `type` silently posted the parent
form on click — repro on knowledge detail: clicking the
`DetailNavigationButtons` Prev/Position/Next cluster (or the Anonymize
button) fired the form's submit handler and kicked off an
`updateKnowledge` mutation that 502'd. Mirrors the existing convention
in `InputGroupButton`. `asChild` still defers to the consumer's
element; the one genuine submit caller (`FormSubmitButton`) is
explicit. Audit confirms no other Button uses default-submit
intentionally.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
`useDetailNavigation` now owns a controllable local search (debounced,
ANDed with the URL `?q=` filter) and `DetailNavigationSheet` surfaces it
as a header input by default (`hasSearch={true}`). Sheet auto-focus no
longer steals focus from the search input when `filteredItems` shrinks
on a debounce flush — gate the option-focus effect on `document.activeElement`
so typing past the boundary keeps the caret in place. ArrowDown from the
input synchronously promotes focus into the listbox.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Now that `useTableState` no longer touches storage for filter values, the
adjacent read-only API has dead optionality:
- `useTableQueryFilterReader` accepted a `storageKey` that was already
documented as "ignored here — only for API symmetry with the mutate
variant." With the symmetry gone (the mutate variant no longer takes
one), keep the reader pure-URL and drop the prop entirely.
- `useDetailNavigation` used to compute that storage key via
`usePageStorageKeys` just to pass it into the reader. The whole
`parentPath` override existed solely to feed that computation. Drop
`parentPath`, the `ParentPath` template-literal type, and the
`usePageStorageKeys` import — no caller passes `parentPath`, so the
cleanup is API-compatible.
- `useResourcesSearch` JSDoc still claimed a "localStorage fallback";
reword to describe the current URL-only behavior so the comment stops
contradicting the code.
Manually verified `/knowledges?q=Jinja` → click a row → the detail page
shows `1/11` navigation, Next steps through siblings, and `?q=Jinja`
stays in the URL — the headless controller still reads the live filter
through the reader.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The previous `useTableState` mirrored `?q=` into per-page localStorage
and replayed it back into the URL on mount when the URL came in clean.
The intent was "fresh tab resumes the prior search," but in practice
the storage→URL replay leaked the user's most recent filter into
unrelated visits: navigating away from a filtered `/flows?q=` and
returning via the sidebar would silently land on the same filter, often
with an empty result set the user had no reason to expect.
Filter is an ad-hoc query, not a preference. Real preferences (sorting,
column visibility, page size, search columns) still persist via
`lib/table-state` — only `filter` is dropped from the storage roundtrip:
- Remove the storage→URL restore effect.
- Remove the URL→storage write effect for `filter`.
- Drop the `skipRestore` option (no restore left to suppress) and the
`storageKey` override that only existed to scope the restore.
- Drop the conditional `skipRestore` plumbing on `/knowledges` — the
page no longer needs to defend against a stale `?q=` being replayed
on top of a fresh `?qs=` link.
- Rewrite the "storage roundtrip" test block as
"filter is URL-only": assert the storage entry is ignored on mount,
the URL still wins when both are set, and typed filter never lands
in storage.
Manually verified in the browser: `/flows?q=IDOR` → navigate away →
return to `/flows` shows the unfiltered table; sorting a column still
persists across reloads (`table_4_/flows` keeps the `sorting` field).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The Flows, Providers, and API tokens pages each defined a local
`formatDateTime`/`formatFullDateTime` pair (~16 lines × 3 files) doing
essentially the same trimming-by-recency job as `formatDate` from
`@/lib/utils/format`, and each wrapped the cell in a Tooltip that
repeated the same text more verbosely.
After the previous date-format unification commit (1806956), the
trimmed cell already conveys enough context for every recency band:
- today → HH:mm:ss
- this year → HH:mm, d MMM
- older → HH:mm, d MMM yyyy
So the Tooltip+full-timestamp pair no longer adds information for the
date columns. Replace the three local copies with a direct
`formatDate(new Date(dateString))` call and drop the Tooltip wrapper
where it only mirrors the cell.
The Tooltip on the Terminals column in flows.tsx is kept — it expands
the list of terminals with per-row connection status and is not a
duplicate.
Net delta: -115 / +10 lines.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- providers/flow-provider: map "no rows in result set" to a friendly
"Flow not found" toast with a stable id so repeated sibling-query
errors no longer stack raw SQL into the UI
- components/ui/sidebar: skip the global Ctrl+B shortcut when focus is
in an input, textarea, select, or contenteditable — was hijacking the
Tiptap Bold shortcut in the markdown editor
- components/ui/sidebar: mark the mobile drawer with group + data-state
"expanded" so `group-data-[state=...]` selectors collapse correctly
and flow id badges stop rendering twice in the drawer
- pages/templates/template: add aria-label + title to the icon-only Save
button and mark the icon aria-hidden
- pages/settings/settings-api-tokens: render the date-picker label with
date-fns format "d MMM yyyy" to match the table's date format
- pages/settings/settings-providers: drop the fixed Name column width so
the Type column stays visible on narrow viewports; Badge truncates
cleanly with whitespace-nowrap and shrink-0 on the provider icon
- components/shared/confirmation-dialog: derive the title from
`\${confirmText} \${itemType}` so dialogs surface "Delete template"
instead of a generic "Confirm Action", and use the verb in the
description for consistency
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- DataTableFilter no longer renders a leading `<Search>` addon. With
`InputSearch` now living in the same page header as the trigger for
semantic search, two magnifier icons next to each other read as
visual clutter — the placeholder text alone already cues the input's
purpose. Drops the unused `Search` import too.
- The "Flags" column header span gets `w-full` so its
`justify-end` actually pushes the label flush against the right edge
of the cell. Without the explicit width it collapsed to content
size and the alignment had no axis to act on.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Typing fast into the knowledges header search dropped characters: each
keystroke went straight into the parent's `onSearchChange`, which on
this page funnels through `setSearchParams` → router re-render → the
controlled `searchQuery` prop snapped back through React. When the
round-trip outran the user's fingers, the input's visible value rolled
back and chars between commits were lost ("find" → "fn").
Mirrored the `DataTableFilter` pattern: hold a `localValue` state that
keystrokes update synchronously, debounce the commit upstream
(`useDebouncedValue`, 150 ms — same constant as the table filter so
both inputs on this page feel uniform), and reconcile external resets
(Esc, programmatic URL wipe, back button) via a `lastEmittedReference`
guard that ignores our own round-trips.
Blur and Escape now also read `localValue` instead of `searchQuery` so
keystrokes pending in the debounce window aren't treated as "nothing
typed yet". Escape additionally fast-paths an empty commit upstream so
the clear hits the parent without waiting for the debounce.
Measurements (chrome-devtools, 19-keystroke burst): pre-fix typing
dropped characters, post-fix avg keystroke 2.07 ms, p95 6 ms, 0
keystrokes over the 16 ms 60-fps budget. Server `searchKnowledge`
still fires exactly once per typing pause.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- Kbd inside tooltip-content now uses the `accent` token family
(`bg-accent/20`, `text-accent-foreground`, dark `bg-accent/50`) for
better legibility against the popover background. The previous
`bg-background/20` chips read as thin film on dark tooltips.
- The empty-state "New Knowledge" button on the knowledges page passes
`<Plus />` without an explicit `size-4` — the Button variant already
sizes its icon slot, the override was duplicating defaults.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Children like Kbd target tooltip surfaces via
\`[[data-slot=tooltip-content]_&]:bg-background/20\` selectors so the
chips can re-tone themselves for the dark popover background. Our
TooltipContent was missing that attribute (the file shipped from a
pre-v4 cut of shadcn), so the override never matched and Kbd kept its
muted page-surface styling — invisible on the tooltip.
Set \`data-slot\` on every Tooltip primitive (provider / root /
trigger / content) to match the v4 contract. Verified in DevTools:
Kbd inside tooltip-content now computes the inverted background and
foreground colors.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
shadcn ships the canonical Kbd-inside-Tooltip pattern (per the
upstream kbd-tooltip demo and our existing components/ui/kbd.tsx).
The Kbd component already self-themes for tooltip-content surfaces
via `[[data-slot=tooltip-content]_&]` overrides, so swapping the
plain "(⌘ K)" suffix for `<KbdGroup><Kbd>⌘</Kbd><Kbd>K</Kbd></KbdGroup>`
matches the rest of the app and renders proper keycap chips against
the tooltip background.
Verified the accessibility-description path: Radix still surfaces the
flattened "Semantic search... ⌘ K" string to screen readers (we saw
it in the a11y snapshot), so the keyboard hint stays announced.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The collapsed trigger is just a magnifier icon — there's no visible
hint about what it does or which key reveals it. Added a tooltip that
combines the `placeholder` with the platform-appropriate hotkey glyph
(⌘ on Apple, Ctrl elsewhere) using the existing `isMac()` helper. When
`hotkey` is `null` the suffix drops and the tooltip shows just the
placeholder.
Tooltip wraps only the trigger button: once the input is expanded the
caret is in it and a hovering tooltip would obscure the very thing the
user is typing into.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The original sofy-front version collapsed the control whenever focus
left an empty input. When the duplicate blur+effect pair was folded
into a single effect during the port, that behaviour silently went
with it — opening the trigger without typing and then clicking
elsewhere left the box expanded forever, because `searchQuery` never
changed and the effect never re-ran.
Re-added a dedicated `onBlur` handler that collapses on focus loss
when the value is empty. The effect stays as the safety net for the
programmatic-clear case (parent wipes `?qs=` from the URL while focus
is elsewhere) — different trigger, different path, neither path can
cover the other.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
`HeaderButton` defaults to `size='sm'` (h-8 px-3 rounded-md text-xs)
and pages mount InputSearch right next to it. The component previously
shipped with h-7 / icon-xs (28 px) so the icon-only trigger sat a
notch shorter than its sibling action — visible in the knowledges
header.
Bumped the group to h-8, the trigger to size='icon-sm', and pinned
the inner input to h-8 (it inherits `Input`'s default h-9 otherwise,
which pokes 4 px past the bordered group). Dropped the duplicate
negative margins on the button — the addon's
`has-[>button]:ml-[-0.45rem]` already handles flush-left alignment
when expanded; only the collapsed state needs the explicit `-mx-1.5`
to claw back the addon's default padding around the lone icon.
Verified: trigger 32×32, group 32 px, input 32 px, all matching the
neighbouring `HeaderButton` baseline.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
New `components/ui/input-search.tsx`: a controlled, collapsible search
control that idles as just a `<Search>` icon button and expands into a
text input with a motion-driven width animation. Adapted from the
sofy-front version with:
- Trigger is a real `<button>` (via `InputGroupButton`) instead of a
`<div onClick>` — keyboard reachable, screen-reader announced, and
avoids the invalid-HTML nesting that putting an `<input>` inside a
`<button>` would create.
- Configurable Mod+`hotkey` (default `'f'`, `null` to disable). The
knowledges page uses `'k'` so it doesn't fight the browser's own
Ctrl+F find-in-page.
- Escape clears the value on the first press, blurs + collapses on the
second — matches native search-input muscle memory.
- Single collapse effect on `searchQuery` change instead of the
duplicate blur+effect pair.
- `aria-label` prop wired to both the trigger button and the input.
The knowledges header now mounts this control bound to `?qs=` via
`useSearchParams`. The provider already debounces the URL value before
hitting `searchKnowledge`, so the input commits keystrokes immediately
(instant UI feedback) while the server roundtrip waits for the 400 ms
debounce. URL writes use `replace` to avoid history-stack churn.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
When `/knowledges` is opened via a `?qs=…` link, `useTableState`'s
mount-time restore was injecting the previous session's `?q=` from
storage on top of it — so a clean semantic-search URL silently became
`?qs=foo&q=python` and the user got a narrowed result set they didn't
ask for.
Added `skipRestore` to `useTableState` (defaults to `false`, captured
via a ref at mount so a later toggle doesn't replay a restore the user
has worked past). `knowledges.tsx` passes `searchParams.has('qs')` so
the restore is skipped exactly when the parameter is part of the
landing URL.
Mirror-to-storage on subsequent filter changes is unaffected — a
client filter the user actually types still persists to storage for
the next session.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Knowledges list previously sourced everything from `knowledgeDocuments`.
When `?qs=` is present the provider now switches to `searchKnowledge`
(debounced 400ms, capped at 100 results) and feeds the resulting subset
through the same public `knowledges` array — so DataTable, the existing
`?q=` client filter, and DetailNavigation continue to walk it without
any consumer-side change.
Subscription cache merge in `lib/apollo.ts` only covers the
`knowledgeDocuments` root field; in search mode CRUD events trigger a
`refetchQueries(['searchKnowledge'])` via `useLatestRef` so the relevance
ordering stays consistent without freezing the boolean at mount.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Mirrors the entry already present in the right-click context menu so
both menus expose the same set of actions (Edit / Copy Token ID /
Delete) — the dropdown was previously missing the copy shortcut.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Long-press on iOS/Android starts native text selection before Radix
ContextMenu reacts, so the row appears highlighted from the top of the
table down to the finger. Apply `user-select: none` and disable the iOS
callout on those rows only, and only on coarse pointers — desktop users
keep the ability to select cell text with the mouse.
Pattern matches the workaround discussed in radix-ui/primitives#930.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Hover relies on the cursor staying over the <tr>, but Radix portals the
overlay so the row dims as soon as the menu opens. Match the same
background via `data-[state=open]` (ContextMenuTrigger forwards
`data-state="open"` onto the row through `asChild`) and
`has-[[data-state=open]]` (covers any Dropdown/Popover triggered from a
cell). Switch the selection prop to a conditional spread so the prior
`data-state={false}` no longer wins over Radix Slot's merged props.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Single source of truth for every route's tab title. All title knowledge —
static strings, params-derived resolvers, and Apollo-cache-driven reactive
components — now lives in src/lib/route-titles/, and app.tsx imports only
the `routeTitles` object. The router file no longer pulls Apollo hooks
or formatters; it just spreads handles onto routes.
Handle API collapsed from two keys to one. Following the canonical
`useMatches` example from React Router docs, `handle.title` is now a
single field that accepts three forms:
• `string` — static, known at build time
• `(params) => string` — synchronous resolver from URL params
• `ComponentType<{ params }>` — reactive (e.g. Apollo cache subscription)
DocumentTitle distinguishes resolver vs component by the PascalCase
convention (component names start with an uppercase letter), so the
choice is implicit at the call site — no `titleComponent` field, no
discriminated union, no marker property.
Boilerplate consolidation:
- 4 near-clone resource-title components (Flow/Knowledge/Provider/
Template) collapse into 4 declarative `apolloTitle({ useQuery,
variables, select })` calls in the registry. The factory owns the
`fetchPolicy: 'cache-only'` plumbing, skip semantics, and component
naming.
- renderTitle/APP_NAME/RouteParams were duplicated between
document-title.tsx and resource-titles.tsx — now imported from one
render-title.tsx.
- formatPromptId moves into the route-titles module since the prompt
detail page and the route handle are its only consumers.
References to React docs added to document-title.tsx: only one <title>
should be rendered from React at a time (multiple → undefined browser/
SEO behavior). The convention is now enforceable from one place.
All 482 unit tests pass; lint, tsc, prettier clean. Verified in the
browser across every route — static (Dashboard, Flows, Resources, …),
/new variants (New flow, New provider, …), params resolver
(/settings/prompts/agentSelector → "Agent Selector"), and Apollo
reactive (/flows/491 → "Flow #491 — Login Beta Program"), including
sibling navigation between detail routes which previously motivated
moving DocumentTitle into the shell.
Net diff: -171 / +66 across the touched files plus the new registry.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Match the redirect pattern used on the flow page: instead of rendering
a dedicated "not found" card with a manual back button, show a toast
and replace the route with /knowledges so the user lands on the list
the same way other resources behave.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Single mechanism for the document <title>. Every route now declares its
title in the react-router handle:
• handle: { title: 'Dashboard' } — static listing pages
• handle: { title: (params) => formatPromptId(params.promptId) } —
params-derived (e.g. /settings/prompts/:promptId)
• handle: { titleComponent: TemplateTitle } — Apollo cache-driven,
reactive to cache updates after the page mounts
A single <DocumentTitle/> in RootLayout walks useMatches() and picks
the deepest match. PageTitle is gone — 13 call sites across 13 page
components migrated to handle, the component deleted.
Other improvements:
- Split document-title.tsx so the shell-only <DocumentTitle/> has zero
graphql imports — the resource title components (FlowTitle,
KnowledgeTitle, ProviderTitle, TemplateTitle) live in
resource-titles.tsx. This lets the unit tests render DocumentTitle
without dragging the codegenerated graphql/types.ts through Vite.
- String(p.id) === providerId replaces sloppy == in ProviderTitle.
- matches.findLast(...) replaces the imperative for-loop.
- Extracted formatPromptId into lib/utils/format-prompt-id.ts so the
prompt detail page and the route handle resolver share one formatter.
7 unit tests added for DocumentTitle covering: static title, derived
title from params, deepest-match-wins, titleComponent rendering,
titleComponent precedence over static title, empty-string fallback,
and no-handle fallback.
19 test files / 482 tests pass; lint + tsc clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Move <title> ownership out of detail-page components into the app
shell. The four detail routes — templates/:templateId,
knowledges/:knowledgeId, settings/providers/:providerId,
flows/:flowId — now expose a titleComponent via react-router
handle. A new <DocumentTitle/> in RootLayout walks useMatches()
deepest-first and renders the matched title component. Each one
subscribes to its resource via Apollo with fetchPolicy:
'cache-only', so it reacts to the destination page's own fetch
without issuing a duplicate request.
Fixes the root cause behind bbf943e's sticky workaround: navigation
between sibling documents (DetailNavigation prev/next) tore down
the page-level state that PageTitle held, flashing a generic
fallback during data fetch. The shell-level <DocumentTitle/>
survives the remount, so the title resolves from cache before the
new page has finished mounting.
- Add src/components/shared/document-title.tsx with DocumentTitle
plus FlowTitle / KnowledgeTitle / ProviderTitle / TemplateTitle.
- Wire <DocumentTitle/> into RootLayout and attach
handle={{ titleComponent: ... }} on the four detail routes.
- Remove <PageTitle> calls and now-redundant <> wrappers from the
four page components.
- Drop the sticky setState-during-render hack from PageTitle —
listing pages that still use it never flickered, so the simple
passthrough is enough.
Lint + tsc clean, all 475 tests pass. Listing routes (Dashboard,
Flows, Templates, Knowledges, etc.) keep using PageTitle and can
migrate route-by-route without coordination.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Replace the two ad-hoc useState form objects (createFormData /
editFormData) in settings-api-tokens.tsx with parent-level useForm
hooks per inline row, each backed by a zod schema. Controller in
each DataTable cell re-subscribes to the parent form state on
remount, so subscription-driven row remounts no longer drop user
input — same root cause that 04c6825 fixed, but solved at the
architectural level instead of controlling each Input manually.
- tokenNameSchema (trim + max 255), createTokenFormSchema with
required expiresAt via refine, editTokenFormSchema with status.
- <Input>, <Select> and <Calendar> cells rendered through
<Controller>; RHF owns the values, not React state in the parent.
- CreateRowActions / EditRowActions subcomponents own the
useFormState({ control }).isValid subscription so the Save button
re-renders only the small action subtree on keystrokes instead of
the whole table.
- Ad-hoc required/trim checks dropped from handlers; the schema +
isValid gate handle them. Submit still applies trim() || null
because the GraphQL mutation treats null as "no name."
All 18 test files / 475 tests pass; lint + tsc clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Manual formatting pass plus a UI tweak that turns the DataTable
"Columns" trigger into an icon-only ColumnsSettings button to match the
other toolbar controls' compact look. The button keeps its accessible
name via aria-label="Columns" so screen readers and
data-table.test.tsx (`getByRole('button', { name: /Columns/ })`) still
find it. Other touched files are pure prettier reformatting.
All 18 test files / 475 tests pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The /providers/new, /knowledges/new and /templates/new routes shared the
generic fallback used during data loading on their respective detail
pages, so the browser tab read "Provider — PentAGI", "Knowledge —
PentAGI" or "Template — PentAGI" while the user was clearly creating a
new entity. /flows/new already did this correctly ("New flow — PentAGI")
and serves as the reference.
Each detail page already exposes an `isNew` flag derived from the route
param, so the fix is a one-line branch in each PageTitle call site:
/settings/providers/new → "New provider — PentAGI"
/knowledges/new → "New knowledge — PentAGI"
/templates/new → "New template — PentAGI"
Verified in chrome-devtools MCP — all three tabs now show the new
titles.
While here, give PageTitle a sticky fallback: once a non-empty title is
rendered, briefly empty children (e.g. a data refetch on the same
route) keep showing the previous value instead of flashing the generic
"Provider/Knowledge/Template — PentAGI" fallback. This helps in-route
loading transitions; it intentionally does not survive route remounts
(navigating Prev/Next between sibling documents tears down the Template
component and the local state with it). A complete fix for the inter-
route flicker requires app-level state or an optimistic Apollo cache
read on mount and is out of scope here.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The Analytics tab on /dashboard renders 4 Recharts plus a Flow
Execution Details list with 130+ Collapsible rows. Switching the period
(Week/Month/Quarter) re-rendered everything synchronously: the
pointerdown→paint interaction had INP=434ms (Google "Needs Improvement"
zone), with processing duration alone accounting for 403ms.
Four small changes, no new dependencies:
1. useMemo on usageChartData / toolcallsChartData / flowsChartData so
Recharts receives stable references when only an unrelated piece
of parent state changes (e.g. tooltip hover state).
2. useDeferredValue(executionStats) so a period switch can repaint
the charts first and reconcile the long list as a low-priority
follow-up. While the deferred value is stale we dim the list to
60% opacity, matching the existing dashboard.tsx convention.
3. content-visibility: auto + contain-intrinsic-size on every
FlowExecutionItem. Off-screen rows skip layout and paint entirely
— this is the cheapest possible virtualization, with no deps,
measurement, or scroll math.
4. React.memo on FlowExecutionItem and TaskExecutionItem so parent
re-renders don't traverse the entire 130-row tree.
Measured via chrome-devtools MCP performance trace:
Before: INP 434ms — input 1ms / processing 403ms / present 29ms
After: INP 134ms — input 1ms / processing 112ms / present 21ms
CLS stays at 0.00.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The inline create/edit row in the API tokens table used uncontrolled
<Input ref={…} defaultValue="…" /> and read the value back from the ref
inside the submit handler. When the apiTokens subscription fired during
the user's interaction, DataTable would reorder rows and the input would
re-mount with defaultValue="" (or the original name), discarding what
the user just typed. The mutation then sent name: null and the freshly
created token appeared as "(unnamed)".
Move both create and edit name inputs to controlled state, drop the
two refs, and read the value from form state at submit time so it
survives any number of re-mounts. While here, give each input a stable
useId() for id, an explicit name="token-name", and autoComplete="off"
to silence the "A form field element should have an id or name
attribute" Chrome DevTools issue that this form was triggering.
Verified via chrome-devtools MCP: creating a token named "qa-pr1-verify"
now stores and displays the name correctly across the
useApiTokenCreatedSubscription refetch.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two long-running mutations now flip the UI on the urgent track and
reconcile against the server in the background, so the user no longer
sees the latency between a confirming click and the network round-trip.
pages/flows/flow.tsx — inline rename
- New optimistic title state seeded from `flow.title` and updated via
`setOptimisticFlowTitle(next)` at the start of the save handler.
- Mutation runs inside `startTransition(async () => …)` so React keeps
the optimistic title visible while awaiting the rename. On success
the Apollo cache update lands and useOptimistic falls back to the
fresh `actualFlowTitle`; on failure the toast surfaces and the value
rolls back to the cached title automatically.
providers/favorites-provider.tsx — toggle favorite
- `useOptimistic` over the favorite-ids array with an `add`/`remove`
action reducer. addFavoriteFlow and removeFavoriteFlow wrap their
Apollo mutations in `startTransition` and call
`applyOptimisticFavorite` first, so the sidebar's Favorite Flows
list and the row's star both flip instantly.
- Subscription-driven cache refresh still arrives a moment later and
becomes the new `actualFavoriteFlowIds`; React's transition exits
without a visible flicker because the optimistic value already
matches what the cache now holds.
Verified: build, lint (0/44 baseline), 475/475 tests, browser smoke —
clicking the favorite star on /flows immediately moves the row into
"Favorite Flows" in the sidebar and back, no console errors.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Reworks the FormSubmitButton so it slots into every Button use-case
in the codebase, not just the simplest text-only submits:
- Adds an `icon` prop. While the form is idle the icon renders to the
left of `children`; while submitting it is swapped for the spinner
in place, so the button keeps its layout. Plain text buttons stay
the same — the spinner is prepended only during submit.
- Adds an optional `loading` prop. When provided it wins over
`formState.isSubmitting`, which unlocks two real cases we
previously had to skip: submits attached via the HTML `form="…"`
attribute that live outside the FormProvider tree, and submits
whose pending state is the union of several mutation flags.
- Reads `useFormContext()` defensively — it returns null outside
a FormProvider, so the component degrades to "controlled by
`loading` prop only" instead of throwing. That keeps the API
honest for both in-tree and out-of-tree submits.
All other Button props (variant, size, className, onClick,
aria-label, form, …) pass through unchanged because the type
extends `React.ComponentProps<typeof Button>`.
Applied to two more previously-skipped sites:
- settings-provider.tsx Save button (form="provider-form",
loading=isLoading union, Save icon, dynamic label).
- settings-prompt.tsx system and human Save buttons (same shape).
resources-mkdir-dialog now passes FolderPlus via the new `icon`
prop instead of putting it inside children, so the dialog's submit
spinner replaces the folder icon in place during submit.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
New shared component src/components/ui/form-submit-button.tsx. It is
the react-hook-form-flavoured analogue of React 19's useFormStatus:
the button subscribes to the nearest FormProvider via useFormContext
and reads formState.isSubmitting / isValid / isSubmitted itself, so
the surrounding form no longer has to thread loading flags down.
Shows a Loader2 spinner while submitting and disables itself once
the form is dirty-and-invalid (opt out with requireValid={false}).
Applied to the three forms where the submit is a plain
<Button type="submit"> living inside a <Form {...form}> wrapper:
- login-form.tsx — also dropped the manual isSubmitting toggles
inside the form handler (RHF already tracks that through
form.handleSubmit). Kept the OAuth-flow useState because the
provider login does not go through form.handleSubmit; combined
the two states on the OAuth buttons so they also disable while
the form is submitting.
- password-change-form.tsx — dropped the manual isSubmitting state
entirely; the only submit goes through form.handleSubmit. Cancel
and Skip buttons stay as plain Buttons.
- resources-mkdir-dialog.tsx — replaced the submit button; kept the
isCreating flag because Cancel and the Input still need to react
to the mutation in flight.
Five other forms intentionally kept their current submit:
- knowledge-form.tsx uses our HeaderButton (responsive icon/label)
with its own Spinner, not a plain Button.
- flow-form.tsx and templates/template.tsx use InputGroupButton
(icon-only, sits inside an InputGroupAddon).
- settings-prompt.tsx and settings-provider.tsx attach their submit
to the form via the HTML form="…" attribute, so the button is
outside the FormProvider tree — useFormContext would throw.
These also drive disabled state from multiple mutation flags
(create/update/delete/validate) that aren't reducible to a single
isSubmitting.
Verified: pnpm run build, lint (0/44 baseline unchanged), 475/475 tests.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Three nearly-identical calendar icons (CalendarDays / Calendar /
CalendarRange) didn't convey Week vs Month vs Quarter clearly on a
375 px viewport — the differences between the glyphs are too subtle
at 16 px. Swapped them for the first letter of each label (W / M / Q)
with the same compact `size-7` button shape; full label stays on
sm+ as before.
Kept aria-label on the trigger and aria-hidden on the letter span so
screen readers still announce the full word.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The mobile period switcher swap landed in 28c98a8 but kept the
text-button paddings (px-3), so each "icon-only" trigger was still
~36 px wide and the group looked stretched on a 375 px viewport.
Added \`aspect-square px-0\` to each TabsTrigger (with the desktop
overrides reset above the \`sm\` breakpoint) so the buttons collapse
to a 1:1 ratio on mobile — three tight squares matching shadcn's
icon-button proportions — while desktop keeps the original
horizontal padding.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
On screens narrower than the `sm` breakpoint (640 px) the
Week / Month / Quarter triggers were forcing the period switcher to
crowd the Analytics / Overview tabs into the next line. Replaced
the labels with lucide calendar icons (CalendarDays / Calendar /
CalendarRange) that swap in below `sm` while the full text comes
back above it.
Accessibility preserved — each TabsTrigger keeps an explicit
aria-label and the icons are aria-hidden so screen readers still
announce "Week" / "Month" / "Quarter" instead of duplicate icon
descriptions.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Both tab groups on /dashboard trigger expensive re-renders:
- Analytics ↔ Overview swaps the entire content subtree (Analytics
alone pulls in a ~386 kB chunk with four Recharts views).
- Week / Month / Quarter invalidates the analytics query and
re-paints every chart with the new dataset.
Wrapped both setState calls in startTransition so the trigger
buttons update on the urgent track while the heavy work commits as
low-priority. React will discard intermediate frames if the user
clicks again before the previous transition finishes.
Surfaces the combined isPending state via a subtle opacity-60 dim
plus aria-busy on the content region — gives users feedback that
the heavier render is in flight without a spinner flash.
Verified: build, lint (0/44 baseline), 475/475 tests, browser smoke
on /dashboard with no console errors after switching periods.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Brings every top-level React component and hook outside of
src/components/{ui,shared} (those were already migrated in 9d5daf7)
in line with the shadcn/ui new-york-v4 canonical style:
- features/* (flows, knowledges, resources, authentication, …)
- pages/* (dashboard, flows, knowledges, settings, templates, login,
oauth-result, resources)
- providers/* (all eleven context providers + their useXxx hooks)
- components/icons/* (every SVG icon + provider-icon, flow-status-*)
- components/layouts/* and components/routes/*
- hooks/* (use-* hooks in their own files)
- Calendar UI component (missed in the earlier pass — also dropped
the redundant `displayName = 'Calendar'` and the empty
`CalendarProps = DayPickerProps` alias)
Net diff is +50 lines (1842 ins / 1792 del — the lines that were
removed are the `const X = (…) =>` declarations and the matching
closing `;`, plus a handful of explicit `React.FC<…>` type
annotations that no longer add anything; the lines added are the
`function X(…) {`/`}` envelopes).
What we deliberately did NOT touch:
- Inner components/hooks defined inside other functions — keep their
arrow form so the local-scope intent stays visible.
- React.memo / React.lazy wrappers — `const X = memo(InnerX)` and
`const X = lazy(() => …)` aren't components themselves.
- Render-callback props (renderFlowItem, renderItem, …).
- Plain utilities, helpers, factories, REST/GraphQL builders and
every file under lib/, models/, schemas/, types/, graphql/types.ts.
- The few callback-ref-composing components (autocomplete, textarea,
markdown-editor) keep their explicit `ref?: Ref<CustomShape>`
because ComponentProps can't express their custom imperative shape.
Bonus cleanup along the way: removed the now-unused
`import * as React` from settings-prompt.tsx (was only there for the
deleted `React.FC` typing).
Verified: pnpm run build, lint (0 errors / 44 warnings unchanged
baseline) and 475/475 vitest tests.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Removes two leftover `X.displayName = 'X'` lines that just duplicated
the function's own name:
- src/components/shared/terminal/terminal.tsx
- src/components/shared/monaco-terminal.tsx
Two other displayName usages in the wider codebase are kept on
purpose:
- markdown.tsx — factory creates an inner `Renderer` and stamps it
`Highlighted(${ComponentName})` so each instance shows up
distinctly in React DevTools.
- file-manager-row.tsx — the function is named `FileManagerRowImpl`
and re-exported through React.memo as `FileManagerRow`; the
displayName carries the public name across the memo wrapper.
The five `.displayName` mentions in src/pages/settings/settings-prompt*
are property reads (`promptInfo.displayName`, `row.original.displayName`)
on domain data, not component metadata — untouched.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Brings all 32 components in src/components/{ui,shared} in line with
the current shadcn/ui new-york-v4 canon (cross-checked against the
upstream registry tooltip / button / input / dialog sources). Net
diff is -637 lines of boilerplate.
Four shape changes per component:
1. function declaration instead of `const X = (...) =>`. Slightly
cleaner stack traces and Function.name is set automatically.
2. React.ComponentProps<typeof X> (or React.ComponentProps<"button">
for native elements) instead of
React.ComponentPropsWithoutRef<typeof X> & { ref?: React.Ref<...> }.
In React 19 ref is already part of ComponentProps; the explicit
intersection was leftover noise.
3. `ref` is no longer destructured — it flows through `{...props}`
spread into the underlying primitive. Exceptions kept verbatim:
textarea.tsx (custom TextareaRef shape with useImperativeHandle),
autocomplete.tsx (callback-ref composition in AutocompleteInput
and AutocompleteContent), markdown-editor.tsx (MarkdownEditorHandle
with useImperativeHandle).
4. displayName removed everywhere — Function.name covers React DevTools
now that there is no forwardRef wrapper to hide it.
Verified: pnpm run build, lint (0 errors / 44 warnings unchanged
baseline) and 475/475 vitest tests.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds a tiny <PageTitle> wrapper around React 19's native <title>
element (which React hoists into <head> automatically) and uses it
from every page-level route. Browser tabs, history, and shareable
URLs now reflect the actual page instead of the static "PentAGI"
that index.html ships.
- Static titles for list and form pages (Dashboard, Flows, New flow,
Flow report, Templates, Knowledges, Resources, Providers, Prompts,
API tokens, Login, OAuth).
- Dynamic titles for detail pages — flow title + id, knowledge
question, template name, provider name, prompt display name — with
graceful fallbacks while data is still loading.
- Added to every render branch (loading / error / empty / main) so
the tab title stays correct even before data lands.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Migrates all 32 components in src/components/{ui,shared} from
React.forwardRef<RefT, PropsT> to plain functional components that
take `ref?: React.Ref<RefT>` as a regular prop. React 19 treats ref
like any other prop, so the forwardRef wrapper is no longer needed
and only added boilerplate + an extra type parameter.
Highlights:
- All 32 files keep their displayName so React DevTools and Radix
Slot composition still surface readable component names.
- Custom-shape refs (TextareaRef in textarea.tsx and
MarkdownEditorHandle in markdown-editor.tsx) plus the callback-ref
composition inside autocomplete.tsx are preserved verbatim — only
the wrapper changes.
- sidebar.tsx contained 22 forwardRef wrappers in one file; all
converted in the same pass.
- No behaviour, classes, attributes or imports of `import * as React`
are touched. pnpm run lint:fix afterwards reformatted the auto-added
blank lines so we are back to 0 errors / 44 warnings (baseline).
Verified: pnpm run build, lint, and 475/475 vitest tests.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Wraps the composite globalFilter ({ columns, query }) in
React.useDeferredValue before handing it to TanStack's state. The
filter input itself stays urgent (already debounced to 300 ms), so
keystrokes still feel instant; what becomes low-priority is the
heavy getFilteredRowModel() recomputation that runs over the full
dataset — ≈353 flows, 180 knowledge documents, ~50 templates and
API tokens. On those screens React can now drop intermediate filter
states when the user is still typing, instead of committing each
debounce tick on the urgent track.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- detail-navigation-buttons.tsx: wrap long cn() call across lines
- knowledge-header.tsx: alphabetize lucide-react named imports
- flow.tsx: reorder Tailwind classes per prettier-plugin-tailwindcss
canonical order
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Drops pnpm run lint from 5 errors to 0 (warnings unchanged at 44).
Each disable is the smallest local suppression with a one-line reason
on the same comment, so the next reader sees why the rule was muted:
- src/components/ui/textarea.tsx (line 79): the effect intentionally
syncs the internal auto-size trigger with the controlled value prop
every time the parent changes it.
- src/features/flows/files/use-flow-container-files.ts (line 107): the
effect calls an async fetcher (fetchListing) whose setState runs
after await — not synchronously inside the effect body; pathsKey is
intentionally used in place of the paths array reference.
- src/pages/settings/settings-prompt.tsx (line 344): the useMemo
branches on data.settingsPrompts which the react-compiler can't
statically prove stable.
- src/providers/resources-provider.tsx (line 70): intentional
mount-time loading flag for the REST hydration path.
- src/providers/user-provider.tsx (line 144): refreshAuthInfo's
setState runs after an async /auth/info fetch, not synchronously.
Build, 475/475 vitest tests, and runtime smoke (dashboard, flows,
knowledges, settings/providers) all pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Runs pnpm update + bumps prettier-plugin-tailwindcss 0.7.4 → 0.8.0
(the 0.8 release is the one that pairs with Tailwind v4).
After this commit, pnpm outdated only reports three deliberately
pinned packages: eslint / @eslint/js (held on 9.x while
eslint-plugin-react still targets eslint ^9) and @types/node (held on
24.x to match the Node 24.12 runtime; npm latest is 25.x for Node 25).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Bumps @types/node 22.19.19 → 24.12.4 to match the actual Node 24.12
runtime the project is built and run on. The latest published tag is
25.x (for the not-yet-released Node 25 line); we deliberately stay on
24.x.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Bumps @commitlint/cli and @commitlint/config-conventional from 20.5.3
to 21.0.1. Dev-only — affects the commit-message hook, not the app.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Bumps typescript 5.9.3 → 6.0.3.
Adds compilerOptions.ignoreDeprecations = "6.0" to tsconfig.json so the
existing baseUrl/paths setup keeps working — TS 6 has flagged baseUrl
as deprecated (it will be removed in 7.0). The vite-tsconfig-paths
plugin still consumes the paths mapping; nothing else in the codebase
needed changes.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Bumps eslint-plugin-perfectionist 4.15.1 → 5.9.0.
eslint and @eslint/js are intentionally kept on 9.39.4 (the latest
9.x): eslint 10 changes the rule context API
(contextOrFilename.getFilename is gone) and eslint-plugin-react still
ships only versions targeting eslint ^9 — the v10 upgrade currently
crashes the lint run with "Error while loading rule
'react/display-name'". Once eslint-plugin-react publishes a v10-aware
release we can finish this bump.
perfectionist v5 already supports the eslint ^8.45 || ^9 || ^10 peer
range, so it ships cleanly today and gives us its v5 rule changes
without dragging eslint along.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Bumps vite 7.3.3 → 8.0.13 and vite-tsconfig-paths 5.1.4 → 6.1.1.
Vite 8 ships rolldown (the Rust bundler that replaced rollup) and that
required two fixes:
1. build.rollupOptions.output.manualChunks: rolldown no longer accepts
the { chunkName: [packages] } static object form, so it is now an
(id) => string callback that matches paths under node_modules.
2. src/components/ui/resizable.tsx: switched from the namespace import
`import * as ResizablePrimitive` to named `{ Group, Panel, Separator }`
from react-resizable-panels. The v4 release of that library renamed
PanelGroup → Group and PanelResizeHandle → Separator; rollup's
loose tree-shaking happened to keep the old names working at
build-time, but rolldown enforces the export list and the page
failed at runtime with "Element type is invalid". Public wrapper
exports (ResizableHandle, ResizablePanel, ResizablePanelGroup) are
unchanged so the rest of the app keeps working.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Bumps the codegen stack: cli 6→7, client-preset 5→6, typescript 5→6,
typescript-operations 5→6 (typescript-react-apollo and
near-operation-file-preset only moved within their minor range).
Configures typescript-react-apollo to emit Apollo v4-compatible imports
via apolloReactCommonImportFrom / apolloReactHooksImportFrom set to
@apollo/client/react, so re-running pnpm run graphql:generate now
produces ApolloReactCommon / ApolloReactHooks namespaces from the v4
subpath instead of the v3 single-entry import.
src/graphql/types.ts is fully regenerated under the new config.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Bumps @apollo/client from 3.14.1 to 4.1.9.
Apollo v4 moved React-only exports to the @apollo/client/react
subpath. Updated the three import sites that consume them:
- ApolloProvider in app.tsx
- useApolloClient in providers/resources-provider.tsx
- the Apollo namespace import in graphql/types.ts (covers useQuery,
useMutation, useSubscription, useLazyQuery, useSuspenseQuery,
skipToken, *HookOptions, *QueryResult)
Everything else (gql, ApolloClient, ApolloLink, createHttpLink,
InMemoryCache, Observable, split, NetworkStatus, getMainDefinition,
onError, GraphQLWsLink) keeps its existing import path in v4.
Build output shrunk from 223 kB to 191 kB for the apollo-client chunk.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Bumps zod 3.25.76 → 4.4.3 and @hookform/resolvers 3.10.0 → 5.2.2
(the resolvers v5 requires zod v4).
zod is used in 25 source files (schemas, form validators, table state
parsers). Build passes without changes — the project relies on the
shared subset of the v3/v4 API (z.object/z.string/z.number/z.enum,
z.infer, .min/.max/.optional, refinements). Runtime form validation
keeps disabling submit until required fields are filled.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Bumps react-resizable-panels from 3.0.6 to 4.11.1. The wrapper in
src/components/ui/resizable.tsx only re-exports PanelGroup, Panel and
PanelResizeHandle; their props remain compatible across the major.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Bumps react-day-picker from 9.14.0 to 10.0.1. The Calendar wrapper in
src/components/ui/calendar.tsx uses the v9 classNames keys
(button_next/previous, day_button, range_*, week, weekday, weekdays)
and the components.Chevron API; all of these are preserved in v10.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Bumps marked from 17.0.6 to 18.0.3. Used only in
src/lib/report/report-pdf.tsx for PDF generation via marked.lexer();
that API is compatible across the major.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Bumps lucide-react from 0.553.0 to 1.16.0. The 0.x → 1.x jump is a
versioning policy change, not a breaking API change — all icon imports
keep working as before.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Pin React/React-DOM to 19.2.6 and @types/react* to 19.2.0 in
package.json — lockfile already resolved the latest 19.x; this just
makes the minimum explicit so future installs don't regress.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- Introduced `EMBEDDING_MAX_TEXT_BYTES` to limit the maximum byte size of text sent to the embedding model.
- Renamed database connection pool settings: `DATABASE_MAX_OPEN_CONNS`, `DATABASE_MAX_IDLE_CONNS`, and `DATABASE_VECTOR_MAX_CONNS` for improved PostgreSQL connection management.
- Updated relevant documentation to reflect these new configuration options and their usage.
- Adjusted various components to utilize the new settings for enhanced performance and resource management.
- Added ToolCallLogProvider interface with methods for logging tool calls, updating success and failure statuses.
- Introduced proxyToolCallLogProvider to handle ToolCall logging operations.
- Updated flow execution components to integrate ToolCall logging, including flow workers and controllers.
- Enhanced GraphQL schema to support ToolCall logs, including queries and subscriptions for real-time updates.
- Updated documentation to reflect the new ToolCall logging features and their usage.
- Introduced shared connection pooling for PostgreSQL using `*sql.DB` for sqlc and GORM, optimizing resource usage.
- Added new environment variables: `DB_MAX_OPEN_CONNS`, `DB_MAX_IDLE_CONNS`, and `DB_VECTOR_MAX_CONNS` for configurable connection limits.
- Updated documentation to reflect new connection pooling strategy and provide operational commands for monitoring.
- Implemented shared `pgxpool` for pgvector stores to reduce connection overhead and improve performance.
- Adjusted various components to utilize the new connection pooling setup, ensuring efficient database interactions.
- Introduced WaitTaskCompletion method in FlowWorker interface to block until the current task completes or the context expires.
- Implemented signalTaskComplete to manage task completion signaling across goroutines.
- Added waitFlowCompletion tool to handle waiting for task completion with configurable timeout.
- Updated assistant provider to include wait functionality for flow completion.
- Enhanced templates and tool registry to support new wait functionality.
Gated behind the `anonymize.call` privilege from `useUser()`; runs the
current `content` through the `anonymizeText` GraphQL mutation and writes
the result back. Desktop renders the button before Save; mobile collapses
it into the first item of the actions dropdown (the dropdown now appears
for new documents too when the privilege is present).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The Apollo client's global nextFetchPolicy is 'cache-first', so returning
to /knowledges via SPA navigation would serve potentially stale cache.
Subscriptions are now scoped to /knowledges* and detach on other pages,
so changes from AI agents during flow runs would be missed until a full
reload. Override nextFetchPolicy to keep cache-and-network for this query.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
KnowledgesProvider sat in RootLayout, so knowledgeDocuments (with full
content) and its 3 subscriptions fired on every authenticated page —
a ~2.1 MB payload on /flows, /dashboard, etc. All consumers of
useKnowledges live under /knowledges*, so wrap those routes in a
dedicated layout.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
A paste of multi-KB content into the filter would land in the URL
verbatim (`?q=` plus the raw blob), which exceeds the practical
reverse-proxy limit (~2–4 KB) and breaks the share-link experience.
The user-facing entry point is a single `<input>`, so a DOM-level
`maxLength` is sufficient — it truncates both typing and paste before
the value ever reaches React state, the URL, or localStorage. 200 chars
is well above any realistic search term while leaving plenty of
headroom for non-ASCII expansion under percent-encoding.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The split `useTableQueryFilter` + `usePagination` pair had a latent batching
race: react-router v6 feeds every functional `setSearchParams(updater)`
queued in a single React tick the same pre-batch snapshot, so a `setFilter`
+ `setPage` issued from the same event handler (e.g. a debounced filter
commit landing alongside a paging click) would collapse — the second
write erased the first and `q` disappeared from the URL. The earlier
window.location workaround papered over the symptom for the typical case
but didn't remove the underlying possibility.
Replace both hooks with `useTableState`, which owns filter + pageIndex +
storage roundtrip together and routes every URL write through a single
microtask-coalesced `update(patch)`. When multiple `update` calls fire in
the same tick — `setFilter` and `setPage`, two synchronous handlers, an
effect and a click — they merge into one navigation rather than racing.
Replace conflicts resolve in favour of push, so intentional history
entries (paging) survive coalescence with replace-only updates (filter
typing). The `MemoryRouter` fallback (latest snapshot via ref) is kept
only as a defensive read; the coalescence itself makes it redundant.
A regression test (`two top-level updaters firing in the same tick keep
both params`) locks this in: the previous behaviour failed it, the new
implementation passes it without touching `window.location`.
Read-only siblings stay on `useTableQueryFilterReader` — detail pages
don't write the URL, so no race surface to remove. `usePagination`
deleted entirely; its callers migrated to `useTableState`.
474/474 tests pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
When a debounced filter commit and a paging button click land in the same
React tick, react-router v6 feeds the functional updater of every queued
`setSearchParams` call the same pre-batch snapshot. The second write
overwrites the first instead of stacking, so `setFilter('foo')` followed
by `setPage(5)` collapses to `?page=6` and `q` is lost. The QA pass
caught this on /flows: clicking >> right after typing in the filter
silently dropped `?q=` from the share-able URL.
Build the next `URLSearchParams` from `window.location.search` instead,
since that's the freshest source of truth under BrowserRouter and
sidesteps react-router's batching entirely. Fall back to the latest
react-router snapshot (stashed in a render-synced ref) under
MemoryRouter, which the hook tests use — `MemoryRouter` doesn't sync
its in-memory history to `window.location`.
478/478 existing tests still pass; the browser repro that previously
produced `?page=6` now correctly produces `?q=bypass&page=6`.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Hard-coding the full `table_4_/settings/prompts:agents` / `:tools` keys in
the page duplicated the route prefix that `usePageStorageKeys` already
computes — if the prefix ever bumps (e.g. `table_4_` → `table_5_` on a
storage migration), every call site silently goes stale. Read the route
base from the hook instead and only own the per-table suffix in the page.
Updated the `storageKey` JSDoc on DataTable to document this composition
pattern.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Capture the QA pass we did against the multi-column search rollout:
INP baselines per page, the four bugs we hit (two fixed in the
follow-up commit, two left as backlog), the negative results from
the adversarial input pass (XSS / SQLi / regex meta / unicode /
prototype pollution via localStorage), and the regression scenarios
(S1–S11) so the next round of changes has a concrete checklist
instead of "run it and see if it feels OK".
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two issues uncovered by the QA pass over /settings/prompts, where one page
mounts two DataTable instances:
1. Both inputs shared a hard-coded `id="data-table-search"` and
`name="search"`. `document.getElementById` only ever found the first
one, screen readers couldn't disambiguate the two filter inputs, and
any test selector keyed on the id silently picked the wrong field.
Switch to `useId()` so the id and name are per-instance, non-empty,
and stable across renders.
2. Both tables persisted sorting / column visibility / search-column
narrowing into the same `table_4_/settings/prompts` slot. The last
writer won the race; on reload the loser inherited the winner's
state. Add a `storageKey?: string` prop to DataTable (mirroring the
existing `useTableQueryFilter` API) and pass `…:agents` / `…:tools`
for the two tables on /settings/prompts so they get distinct slots.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
For both the Agent Prompts and Tool Prompts tables, mark every accessor
column with `meta.searchable: true` (name + status fields) and drop the
explicit `filterColumn="displayName"`. Typing "Custom" now surfaces
every prompt currently overridden — a much more useful starting point
than scanning the column visually. Added `columnMenuLabel` overrides
where the underlying accessorKey wasn't human-readable on its own.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Mark `name`, `tokenId`, and `status` with `meta.searchable: true` and
drop the explicit `filterColumn="name"`. The bigger wins are tokenId
(operators often paste a fragment from logs or a request header to find
the owning token) and status (typing "revoked" surfaces every revoked
token without scrolling). Date columns stay excluded.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Mark `name` and `type` with `meta.searchable: true` and drop the
explicit `filterColumn="name"` so users can also narrow by provider
type — typing "anthropic" surfaces every provider of that type without
having to remember its display name. Updated the placeholder to match
the broader scope.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Mark both accessor columns with `meta.searchable: true` and drop the
explicit `filterColumn="title"` so the picker offers both fields and
OR-matches across them. Searching the body text is the bigger win —
template titles are short, so the previous single-column behaviour
missed templates that referenced the same topic in their body.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Mark `docType`, `question`, and `content` with `meta.searchable: true` so
the multi-column picker offers all three as candidates and OR-matches
across them. Drop the explicit `filterColumn="question"` so the
zero-config path (search across all `meta.searchable` columns) takes
over. The `Flags` column has no accessor and would need a custom string
extractor to participate — skipped for now.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Switch the `provider` and `terminals` columns from `accessorKey` to
`accessorFn` so the global filter receives plain strings — the provider
name and the joined list of terminal images — instead of the raw object
or array, which the predicate would just stringify to `[object Object]`.
The cell renderers keep reading `row.original` directly, so the visible
output is unchanged.
Dates stay excluded: substring matching against formatted timestamps
gives unpredictable hits (e.g. typing "3" suddenly matches every row
whose ISO contains 03) and date filtering belongs in a range picker.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Typing into the Flows search felt sluggish — Chrome reported INP 271 ms with input delay 253 ms, meaning every keystroke had to wait for the previous keystroke's render to complete before the event handler could even run. The chain on every keypress was: `setSearchParams` → react-router rerenders the whole route subtree → TanStack re-derives the global filter → 91 rows × 3 predicate calls → reconcile ~70 cells (Tooltip + Badge + ProviderIcon). At ~250 ms per cycle a fast typist queues several keystrokes behind a running render, so the input appeared to lag visibly.
Split the input value from the upstream commit: `DataTableFilter` now owns a local string state that updates synchronously on every keystroke, while a 150 ms debounce mirrors the value into `onQueryChange`. The router / TanStack cascade now fires once per typing pause instead of once per keystroke, and the input never has to wait its turn behind an in-flight reconciliation. After the change Chrome reports INP 43 ms with input delay 2 ms — typing feels instant.
Externally visible behaviour is unchanged: the X button clears immediately (no debounce on explicit clears), and external `query` resets (back button, programmatic clear) sync down through a guarded effect that ignores the value we just emitted ourselves. Vitest tests that previously asserted against the synchronous commit now wait for the debounced row-model update via `findBy*` / `waitFor`.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
`getColumnId` only has one consumer — `lib/` is for utilities shared across the codebase, not for a single-call helper. Move it next to `columnPickerLabel` as a module-level function inside `data-table.tsx`.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The previous implementation drove `searchColumns` narrowing through a regenerated `columns` array with per-column `enableGlobalFilter`. It worked, but every selection change spawned a fresh set of `ColumnDef` objects via spread, invalidating TanStack's column-instance cache and conflicting with the upstream "memoise columns" guidance. The column-id resolver was also duplicated across two memos.
Replace it with TanStack's canonical mechanism for dynamic filters: pack the query and the active column set into a single `state.globalFilter` value of shape `{ columns, query }`, and consult both fields from a custom `globalFilterFn`. Any change to the query or to the active column set produces a new object reference, which is exactly what TanStack watches to re-run the filter pipeline — no imperative `setGlobalFilter` pokes, no closure-only narrowing that silently goes stale, and the parent's `ColumnDef` references reach `useReactTable` untouched so the column cache stays warm. The id resolver moves into a single `getColumnId` helper in `lib/column-utils.ts`.
A regression test exercises the exact sequence that exposed the bug fixed in d4c1b13 (type a query that matches via one column, then uncheck that column — the row must disappear without retyping). A second test pre-seeds `localStorage.searchColumns` with an id that the current columns no longer expose and asserts the new rebase effect prunes it on mount.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The first implementation routed the active-column set through TanStack's
`getColumnCanGlobalFilter` predicate and tried to nudge the pipeline with
`table.setGlobalFilter((current) => current)`. TanStack treats that as a
no-op because the resolved value equals the current state, so the filter
pipeline never re-ran after the user narrowed the picker — the table kept
matching against the previous column set.
Bake the active set into per-column `enableGlobalFilter` via a memoised
`tanstackColumns` instead. TanStack sees a new columns reference whenever
the user's selection changes and refilters automatically, which is the
standard mechanism for this kind of dynamic filter and verified end-to-end
in the browser on the Flows list.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Mark `id`, `title`, and `status` as `meta.searchable: true` so the DataTable picks them up as candidates for the new global-filter search, and drop the explicit `filterColumn="title"` prop so users can search by uuid prefix or by typing a status keyword (e.g. "running"). `provider` and `terminals` stay excluded — both are non-string values that would only emit `[object Object]` matches.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The single-column `filterColumn` prop forced every page to pick one searchable field, which is awkward when a row has several useful text fields (e.g. flows have both `title` and the original `task`). Switch the engine to TanStack's `globalFilter` so the input can match across an OR-set of columns, and add a "Search in" dropdown next to "Columns" that lets the user narrow that set at runtime.
Opt-in stays explicit: `filterColumn: string` keeps the legacy single-column behaviour (no picker), `string[]` activates the picker on the listed columns, and an undefined prop falls back to columns marked with `meta.searchable: true`. The chosen subset persists alongside other table preferences in `table_4_<path>`.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- Added a new SQL migration to insert toolcall privileges into the privileges table.
- Introduced the `ToolcallService` for managing toolcall data, including retrieval of toolcalls and flow-specific toolcalls.
- Implemented API endpoints for fetching toolcalls and toolcall details, with appropriate permission checks.
- Enhanced Swagger documentation to include new toolcall endpoints and their specifications.
- Created a new model for toolcalls, defining their structure and validation rules.
- Added error handling for invalid toolcall requests and not found scenarios.
- Included two new provider YAML files for Qwen 3.6 35B models: `vllm-qwen3.6-35b-a3b-fp8-no-think.provider.yml` and `vllm-qwen3.6-35b-a3b-fp8.provider.yml`.
- Updated Dockerfile to copy the new configuration files into the appropriate directory.
Detail pages duplicated DetailNavigationToolbar's internal navigation
state (prev/next, sheet open, position label) because mobile chrome lives
inside a DropdownMenuItem and could not reuse the toolbar component.
Promote useDetailNavigation to return a full DetailNavigationController,
have the leaf components (Buttons / Sheet / Toolbar) read from it, and
drop the ~40 LOC mobile mirror block on each of three pages.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Plain spans with `text-muted-foreground text-sm tabular-nums` rendered as
loose text floating in the header — visually weak and easy to miss. Wrap
each counter in a `<Badge variant="secondary">` so it reads as a discrete
pill (matches the rest of the design language, e.g. doc-type badges in
the knowledges list).
Touches three locations that all share the icon + title + counter
header pattern:
- `pages/templates/template.tsx`: Preset-templates mobile Sheet header
- `pages/templates/template.tsx`: Preset-templates desktop aside header
- `components/shared/detail-navigation/detail-navigation-sheet.tsx`:
detail-navigation sheet header (Flows / Templates / Knowledges count)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The Preset-templates side panel on `/templates/:id` now mirrors the
header + scrollable body structure of `<DetailNavigationSheet>`, so the
two Sheet surfaces on this page (preset picker and Templates list) look
and behave the same: bordered header row with icon + title + total
counter on the right, scrollable body below.
- Mobile `<Sheet>` and desktop `<aside>` share an identical header
(`border-b p-4` with `FileText`, "Preset templates", and a
`tabular-nums` counter). The mobile variant uses `<SheetTitle>` so
screen readers announce it; the desktop variant uses an `<h3>` styled
to match. The previous `sr-only` SheetTitle is gone.
- Body switches from `<ScrollArea flex-1>` to a plain
`<div className="min-w-0 flex-1 overflow-y-auto">`. Radix `ScrollArea`'s
Viewport wraps children in a `display: table` div whose width grows to
intrinsic content size, defeating `w-full min-w-0` on the inner card
flex rows — the chevron buttons were rendering off-screen on a 390px
viewport because of it. Plain `overflow-y-auto` respects the parent
width and the chevrons land inside the Sheet.
- Each preset Card and its inner flex row pick up `w-full min-w-0`,
the title `<span>` picks up `min-w-0`, so the
`flex-1 min-w-0` title button actually shrinks and `truncate` kicks in
on long preset names. Asides also gain `gap-2` between cards so they
read as discrete items instead of a single bordered run.
- Drop the now-unused `ScrollArea` import.
- `components/ui/scroll-area.tsx`: collapse the `<Viewport>` JSX onto
one line and replace `h-full w-full` with `size-full` — a prettier
cleanup that landed alongside the rewrite.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Both Sheets on the template detail page now follow the same skeleton:
SheetContent (flex flex-col gap-0 p-0)
SheetHeader (border-b p-4)
SheetTitle (flex items-center gap-2 pr-8 text-base)
<icon> <label> <counter on ml-auto>
ScrollArea (flex-1)
<list>
This mirrors `components/shared/detail-navigation/detail-navigation-sheet.tsx`,
so the navigation sheet (Templates 1/8 selector) and the Preset-templates
side panel look and behave the same way on every viewport — same width
cap (`max-w-sm`), same bordered header, same scroll behaviour via Radix
`ScrollArea` instead of plain `overflow-y-auto`.
The desktop `<aside>` variant gets the same skeleton too — wrapped in a
`flex flex-col` so the header strip stays pinned while the preset list
scrolls in the `ScrollArea` below. The pinned header swaps the muted
`<h3>` for the same icon + label + counter line as the mobile sheet, so
the platforms read the same.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Split the panel heading so each form factor gets the title styled for
its container:
- Mobile (`<Sheet>`): use a visible `<SheetTitle>` (no more `sr-only`)
in the sheet's own area, styled at `text-base` to match other Radix
dialog headers in the app.
- Desktop (inline `<aside>`): keep the existing muted `<h3>` outside
the scroll area so it stays pinned while the preset list scrolls.
Lift the title out of `asideContent` so it isn't rendered twice on
desktop; trim the wrapper's `p-4` to `px-4 pb-4` since the title
provides the top spacing in both layouts. Drop `p-2` on `SheetContent`
in favour of `p-0` so the new title can own its own padding.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Radix DialogContent (which `SheetContent` extends) warns when neither a
DialogTitle nor an explicit opt-out is provided, and again when no
Description / `aria-describedby={undefined}` is set. Two places hit
this:
- `pages/templates/template.tsx` preset-templates panel: the visible
`<h3>` lives inside `asideContent` and is reused by the desktop
non-Sheet variant, so add an `sr-only` `<SheetTitle>` inside
`<SheetContent>` for screen readers. Pair it with an explicit
`aria-describedby={undefined}` — the panel is a flat list of presets
with no descriptive sub-text, so opting out is honest.
- `components/shared/detail-navigation/detail-navigation-sheet.tsx`:
already had a `<SheetTitle>` (Flows / Templates / Knowledges), but the
Description warning was still firing. Add the same
`aria-describedby={undefined}` opt-out on `<SheetContent>` — the
listbox of items is self-describing.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Roll the truncate-chain + mobile-navigation pattern introduced for the
/flows/:id page out to every other detail and list page so a long title
never pushes the action buttons off-screen on a ~390px viewport.
Detail pages
- `templates/template.tsx` and `features/knowledges/knowledge-header.tsx`
now mirror `pages/flows/flow.tsx`: left container becomes
`flex min-w-0 flex-1` with `shrink-0` on the SidebarTrigger/Separator,
Breadcrumb/BreadcrumbList/BreadcrumbItem get the `min-w-0` /
`flex-nowrap` chain, BreadcrumbPage gets `truncate`, the right action
area becomes `flex shrink-0`. InlineEditInput in both pages now uses
`w-64 min-w-0 max-w-full flex-1` so the rename input shrinks with the
parent instead of forcing it to ≥256px.
- On `isMobile`, the DetailNavigationToolbar is hidden and re-surfaced
inside the existing actions dropdown as a single row matching
`pages/flows/flow.tsx` (icon + label + Prev/Position/Next button
group with shared borders; middle button doubles as the sheet
trigger). DetailNavigationSheet is mounted separately, controlled by
`isMobileNavSheetOpen` state.
List pages
- `pages/flows/flows.tsx`, `pages/knowledges/knowledges.tsx`,
`pages/templates/templates.tsx`, `pages/resources/resources.tsx`,
and `pages/flows/new-flow.tsx` get the same header truncate chain
preventively — most page titles are short, but the structure stays
consistent across pages and protects against future longer labels.
- `pages/templates/templates.tsx` Title cell gains `max-w-[380px]
truncate` (matched to the existing Text-cell cap) so a long template
title can't blow up the row.
- Settings pages (`settings-providers.tsx`, `settings-api-tokens.tsx`)
don't render a breadcrumb header — their `SettingsLayout` already
shows the sidebar trigger — but their inline header rows still leaked
on narrow screens. Add `min-w-0 flex-1 truncate` to the description
text and `shrink-0` to the Create button so the right-edge CTA stays
visible while the left text degrades gracefully.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Make the /flows/:id page usable on a 390px viewport and replace the two
parallel template/attachment dropdowns with one trigger that works the
same way on every screen.
Header
- Breadcrumb chain (`flex min-w-0 flex-1` on the left container, `flex
shrink-0` on the right one, `min-w-0 flex-nowrap` on BreadcrumbList,
`min-w-0 gap-2` on BreadcrumbItem, `truncate` on BreadcrumbPage) so the
flow title can shrink past its intrinsic width instead of pushing the
action buttons off-screen.
- InlineEditInput: `w-64 min-w-0 max-w-full flex-1` — keeps the 256px
default on desktop but lets the rename input collapse to whatever space
is left on narrow viewports.
- On `isMobile`, the desktop DetailNavigationToolbar and the favorite Star
button are hidden and re-surfaced inside the Flow-actions dropdown:
a single row matching the theme-menu pattern in `main-sidebar.tsx`
(icon + label + Prev/Position/Next button group sharing borders), plus
a separate "Add/Remove favorites" item. The position button doubles as
the sheet trigger, so the mobile navigation has the same affordances as
the desktop toolbar.
Flow form
- Templates and Resources (formerly "Attachments") share one Ellipsis
trigger placed next to the Send button on every viewport — the two
separate FileText/Paperclip dropdowns are gone.
- Inside the dropdown, Radix `<Tabs>` switches between picker panels
rendered above the tab strip; the strip lives at the bottom so it
lands next to the trigger. The dropdown opens upward (`side="top"`
with `align="end"`) and has a fixed `w-72` so it stays inside the
viewport on phone-width screens.
- Tab switch is deferred one tick (`setTimeout(..., 0)`) before
mutating `pickerTab`. Radix DropdownMenuItem listens to `pointerup`
directly, so a synchronous swap let the pointerup that ended the tab
click land on the freshly mounted "Upload files" item in the Resources
panel and fired its `onSelect`.
- Send button gets `shrink-0`; combined trigger picks up `ml-auto` so
Send/trigger stay glued to the right edge without two `ml-auto` items
fighting over leftover space.
Detail navigation primitives
- Expose `DetailNavigationSheet` and `useNavigation` from the package
index so a page can compose its own mobile UI without re-implementing
the filtered-subset / Prev-Next algorithm.
- `DetailNavigationSheet`: add `pr-8` to `SheetTitle` so the trailing
total counter (e.g. "311") stops sitting underneath the absolutely
positioned close button on the right edge.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The hook had exactly one consumer (components/ui/autocomplete.tsx) and
was a tiny ~20-line Radix-style controlled/uncontrolled state mirror.
Move it inline as a private helper next to the component that uses it,
so a future reader doesn't have to chase a one-call hook through hooks/.
useLatestRef stays in @/hooks/ — it's genuinely cross-cutting.
The createTextMatcher helper has only one production consumer
(detail-navigation/use-navigation.ts) and the original 'table-filter'
name implied a tie to <DataTable>'s column filter that the codebase
never actually wired (DataTable still uses TanStack's built-in
'includesString'). Move the file into detail-navigation/ as a private
text-filter module so the matcher lives next to its only caller and the
name reflects what it does (text matching) rather than aspirational
table-filter alignment.
If the table column filter is ever switched to use createTextMatcher
for diacritic folding, the import would simply move back up — but
that's a separate behaviour change, not a naming concern.
Move the lone cycleColumnSort function from lib/table-sort.ts straight
into components/ui/data-table.tsx — it was a one-consumer helper used
only by DataTableColumnHeader, so co-locating it removes the
cross-folder hop without changing behaviour. Exported alongside
DataTableColumnHeader for parity with the shadcn convention and so a
future custom header can reuse the cycle. The four unit tests move
into data-table.test.tsx as a sibling describe block; lib/table-sort
is gone.
Move features/report/ → lib/report/ — the module is mostly pure
utilities (generateReport, generateFileName, copyToClipboard,
downloadTextFile) plus an internally lazy-loaded React-pdf component,
not a feature with its own domain/provider/queries. lib/ is the
honest home; the folder grouping addresses the original audit
complaint of a 658-line .tsx loose in lib/. Consumers swap
'@/features/report' for '@/lib/report'.
The PDF generator (~658 lines, lazy-loaded) and its public-API wrapper
report.ts are functionally one module. They now live together in
features/report/ instead of being scattered in lib/, which was a poor
home for a 658-line React-pdf component anyway. The lazy-import path
inside report.ts stays relative (./report-pdf), and the four consumers
(flow.tsx, flow-files.tsx, flow-report.tsx, resources.tsx) just swap
'@/lib/report' for '@/features/report'.
Note: copyToClipboard and downloadTextFile come along for the ride —
they're generic helpers used in non-report contexts too. Splitting them
out cleanly into lib/ would be worth a follow-up if you want stricter
domain boundaries.
Group inline-rename-input.tsx and use-inline-edit-title.ts into a new
components/shared/inline-edit/ folder, the same pattern we applied to
detail-navigation, overwrite, and unsaved-changes. Rename to drop the
misleading "rename" framing — the API has nothing rename-specific
(autoFocus, busy, defaultValue, onCancel, onSave) and the same component
is used for quick-create and inline-edit flows too:
InlineRenameInput → InlineEditInput
useInlineEditTitle → useInlineEdit
INLINE_RENAME_MAX_LENGTH → inlined as default `maxLength = 200`
Fold the standalone SortableColumnHeader into components/ui/data-table.tsx
and rename it to DataTableColumnHeader (the canonical name from
ui.shadcn.com/docs/components/data-table). The two pieces only ever
shipped together — every consumer paired SortableColumnHeader with
DataTable inside the TanStack column definition. Keeping data-table as
a single file matches the convention already used elsewhere in
components/ui/. Also rename the prop label → title to match the upstream
shadcn signature; touches 20 JSX usages across 5 list pages.
Inside `components/shared/overwrite/` the folder name already supplies
context, so the `-action` suffix is redundant — same principle that
turned overwrite-confirm-dialog into overwrite-dialog. Rename file
use-overwrite-action.ts → use-overwrite.ts, export useOverwriteAction
→ useOverwrite, and the internal UseOverwriteAction* prop/result types
to match. The shape lines up with the project's verb-noun action-hook
convention (useResourcesCopy, useResourcesMove).
Within `components/shared/overwrite/` the folder name already supplies
context, so the file/component names don't need to repeat it. Rename
overwrite-confirm-dialog → overwrite-dialog and overwrite-cta-buttons →
overwrite-buttons (and matching exports OverwriteConfirmDialog →
OverwriteDialog, OverwriteCtaButtons → OverwriteButtons) so the module
matches the file-and-export naming convention used by detail-navigation.
Group the overwrite trio (OverwriteConfirmDialog, OverwriteCtaButtons,
useOverwriteAction) into components/shared/overwrite/ — they cross-import
the OverwriteConflict type and 12 consumers always pull from the same
logical module. Same pattern for the unsaved-changes pair: move the
dialog from components/shared/ and the UI-agnostic guard hook from
hooks/ into components/shared/unsaved-changes/. Each folder ships an
index.ts so consumers reach the module through one import path.
Move the Prev/Position/Next toolbar and its supporting hooks from scattered
locations under components/shared/ and hooks/ into a single
components/shared/detail-navigation/ folder. Rename ListNavigation* →
DetailNavigation* (toolbar/buttons/sheet) so the names reflect what they
actually do — sibling navigation between detail pages, not navigation
within a list. The internal algorithmic hook drops its now-redundant
prefix (useFilteredListNavigation → useNavigation, computeListNavigation →
computeNavigation), and useDetailNavigation moves alongside the toolbar
since it's the public composition layer that produces toolbarProps.
- @react-pdf/renderer (~1.5 MB) moved to an async chunk. lib/report.ts
used to statically re-export PDF helpers from ./report-pdf, which
pulled the entire PDF library into every page that imports
lib/report (flow.tsx, flow-report.tsx). The re-exports are now
async wrappers using `await import('./report-pdf')`, so the
library loads only when the user actually triggers a PDF export.
Initial JS for /flows/:id/report drops from ~2.0 MB to ~500 KB.
- Drop html2pdf.js: zero imports anywhere in the source, but it was
declared as a dependency and reserved a (now-empty) manual chunk in
vite.config.ts. Removing it also drops 22 transitive packages from
the lockfile.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Whitespace, line wrapping and Tailwind class ordering only — no code
changes. Brings 11 files in line with the prettier + tailwindcss
plugin config.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- src/lib/сlipboard.ts → clipboard.ts: the filename used a Cyrillic 'с'
(U+0441) instead of Latin 'c', which made the path silently
unmatchable by anyone typing the import with a Latin letter. Update
the 4 importers in features/flows.
- Delete unreachable settings-mcp-server(s).tsx (~1.3k lines): no
routes registered in app.tsx and nothing imports them. Remove the
matching dead branches and commented menu entry from
settings-layout.tsx.
- Drop unused dev deps simple-git-hooks and lint-staged: no config in
the repo, not used by CI or Docker, hooks were never wired up. Also
remove simple-git-hooks from pnpm.onlyBuiltDependencies.
- Drop unused tsconfig path aliases: @/ui/*, @env (env.ts doesn't even
exist), and @pkg. Only @/* remains.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
When an LLM emits a truncated or malformed arguments field (e.g. "{") instead of valid JSON, downstream consumers such as LiteLLM reject the entire request with a 400 Bad Request, causing the chain to degrade into an infinite retry loop.
- SanitizeToolCallArguments now falls back to "{}" after control-char escaping if the result is still not valid JSON, fixing already-stored chains on restore
- callWithRetries logs a warning and substitutes "{}" at the moment the bad arguments arrive from the LLM, preventing them from ever reaching the database
- Added test cases for truncated JSON, partial objects, and empty strings
- DataTable: route handlePageSizeChange through handlePaginationChange so
onPageChange fires when picking "All" on a high page drops pageIndex to 0.
Without this, the URL kept a stale ?page=N while the display correctly
clamped to "Page 1 of 1".
- DataTable: reconcile effect in controlled mode now compares
externalPageIndex (the URL source of truth) against safePageIndex instead
of the internal mirror, which can drop to 0 via handlePageSizeChange and
hide the URL mismatch from the previous comparison.
- knowledges: add meta.columnMenuLabel to docType and question columns so
the Columns dropdown reads "Type" / "Question" — same labels as the
table headers — aligning with the Flags/Preview entries.
- data-table.test: cover both pathways — out-of-range controlled pageIndex
on mount, and pageSize=All from page 2.
- vitest.setup: polyfill hasPointerCapture / setPointerCapture /
releasePointerCapture so Radix Select interactions don't crash in jsdom.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- DataTable: derive a clamped `safePageIndex` from URL + `pageCount`; use it
for display + reconcile URL via effect when raw differs. Fixes "Page 999
of 31" and "Showing 9981–307 of 307" when a hand-typed URL, a filter
narrowing the dataset, or a pageSize=All bump leaves the URL out of range.
- DataTable: only persist `pageSize` to storage when it differs from
`initialPageSize` so a fresh mount no longer seeds `{ pageSize: 10 }` via
StrictMode dev double-invoke.
- useTableQueryFilter: storage replay no longer drops `?page=` — that flag
belongs to user-driven `setFilter`, not to restoration of prior state.
Out-of-range pages after replay are now handled by the clamp above.
- Settings/Providers + Settings/API tokens: pass `filterValue` / `onFilterChange`
from `useTableQueryFilter` so the filter input is URL- and storage-synced,
matching the pattern used by flows, knowledges, templates, resources.
- InlineRenameInput: export `INLINE_RENAME_MAX_LENGTH = 200` and apply it as
the native `maxLength` attribute. UX guard against paste-bombs that would
break truncation; `defaultValue` is untouched so existing long records
remain editable.
- knowledges: render a "Flags" header for the badges column instead of `null`,
aligning with `meta.columnMenuLabel` and other column headers.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- Added a new SQL migration to insert toolcall privileges into the privileges table.
- Introduced the `ToolcallService` for managing toolcall data, including retrieval of toolcalls and flow-specific toolcalls.
- Implemented API endpoints for fetching toolcalls and toolcall details, with appropriate permission checks.
- Enhanced Swagger documentation to include new toolcall endpoints and their specifications.
- Created a new model for toolcalls, defining their structure and validation rules.
- Added error handling for invalid toolcall requests and not found scenarios.
- Included two new provider YAML files for Qwen 3.6 35B models: `vllm-qwen3.6-35b-a3b-fp8-no-think.provider.yml` and `vllm-qwen3.6-35b-a3b-fp8.provider.yml`.
- Updated Dockerfile to copy the new configuration files into the appropriate directory.
Adds an actions dropdown to the knowledge detail header with inline
rename (double-click or "Rename") and delete with a confirmation dialog.
The form keeps any unsaved edits when an external rename refreshes the
cache (`keepDirtyValues` + reactive `values`), and `onBeforeNavigateAway`
suppresses the unsaved-changes guard right after a successful delete.
The knowledges listing gets the same: a "Rename" item in the row
dropdown and context menu opens an in-row editor, and clicking the row
no longer navigates while a rename is in progress.
Drops the redundant `knowledgeName` prop that was threaded through
`KnowledgeForm`/`KnowledgeLayout`/`KnowledgeHeader` — the header now owns
the title and computes it locally from `knowledge.question`.
Co-authored-by: Cursor <cursoragent@cursor.com>
Adds an actions dropdown to the template detail header with inline rename
(double-click or "Rename") and delete with a confirmation dialog. The
listing learns the same: a "Rename" item in the row dropdown and context
menu opens an in-row editor, and clicking the row no longer navigates while
a rename is in progress.
Co-authored-by: Cursor <cursoragent@cursor.com>
Brings the flow detail page in line with the actions row already available
on the listing: double-click or pick "Rename" from the new actions menu to
edit the title in place, "Finish" to gracefully stop a running flow, and
"Delete" with a confirmation dialog. The listing keeps a `PencilLine`
icon for "Rename" so the action looks consistent across surfaces.
Co-authored-by: Cursor <cursoragent@cursor.com>
Add `HeaderButton` component that renders icon + label on >=768px and
collapses to an icon-only square on narrower viewports, with the
`aria-label` auto-derived from the label so the mobile state stays
accessible. Apply it to the action buttons in Flows, Flow, Knowledges,
Templates, Resources and the Knowledge save button so mobile page
headers stop overflowing.
Co-authored-by: Cursor <cursoragent@cursor.com>
- Added a new SQL migration to insert the 'anonymize.call' privilege into the privileges table.
- Introduced the `anonymizeText` mutation in the GraphQL schema, allowing users to anonymize sensitive text.
- Implemented the `AnonymizerService` to handle text anonymization requests via a REST API endpoint.
- Updated the GraphQL resolver to integrate the new mutation and ensure proper permission checks.
- Enhanced documentation with Swagger and OpenAPI specifications for the new endpoint.
- Added error handling for invalid requests and unavailable anonymizer configurations.
Eliminate the message length truncation from both `putMsg` methods in `aslog.go` and `msglog.go`. This change simplifies the message handling process by allowing messages to be processed without arbitrary length restrictions.
- Fix empty ID bug: langchaingo SimilaritySearch discarded document UUIDs; new SearchKnowledgeDocuments/SearchUserKnowledgeDocuments return them directly
- Remove unsafe fmt.Sprintf SQL filter interpolation, use parameterised queries
- Exclude memory documents from search results at SQL level
- Add FlowID support to passesSearchFilter
- Convert all $N positional params to sqlc.arg(name) across knowledge queries
- Update tests: replace TestBuildSearchFilters with TestPassesSearchFilter, add TestSearchDocuments and TestSearchUserDocuments
cmdk renders a sr-only `<label cmdk-label for={cmdkUseId}>` inside
`<Command>` and points its `for` at a useId it generates for *its own*
input. Our visible input gets its id from `FormControl`'s Radix Slot
instead, so the two ids never line up and Chrome flags "Incorrect use
of `<label for=FORM_ELEMENT>`". Re-point the `for` at the real input id
in a `useLayoutEffect` so the HTML-level association is valid — cmdk
already wires `aria-labelledby` to the same element through Slot, so
screen-reader behaviour is unchanged.
cmdk also hard-codes `aria-expanded={true}` on its combobox input, so
the attribute lies whenever the popover is closed (after Enter,
Escape, outside-click). Pass `aria-expanded={open}` on the inner
`<Input>` — Radix Slot merges child props over slot props for
non-handler attributes, so our value wins and keeps the ARIA state in
sync with the actual popover state.
Co-authored-by: Cursor <cursoragent@cursor.com>
Default the autocomplete filter to a case-insensitive substring match
instead of cmdk's fuzzy `command-score`: in plain autocomplete usage,
returning items whose characters merely appear in order is surprising.
Consumers can still opt back into fuzzy matching via the `filter` prop.
Extract `useControllable` into `@/hooks/use-controllable` (now backed by
`useLatestRef`) so other components can reuse Radix-style controllable
state without redefining it inline.
Replace the plain `<Input>` in the knowledge form's "Code language"
field with `<Autocomplete>` surfacing a curated list of 30 common
languages, while still accepting any free-text value the backend may
expect.
Co-authored-by: Cursor <cursoragent@cursor.com>
Backend now accepts `docType` on `UpdateKnowledgeDocumentInput`, so the
edit form was reworked end-to-end:
- Form schema mirrors REST length limits (content 65536, question 2048,
description 1000, codeLang 100) — GraphQL itself doesn't enforce them.
- `docType` is editable on existing docs, not just on create. Switching
it clears stale subtype values (`answerType`/`guideType`/`codeLang`)
through `setValue` in the Select's `onValueChange`, not via effect, so
freshly loaded documents keep their persisted subtype on first render.
- UPDATE is now a partial payload built from RHF's `dirtyFields`:
untouched optional fields are omitted, cleared fields go out as `""`
so the backend wipes them (previously `'' → undefined` silently
swallowed clears, leaving stale values on the server).
- `KnowledgesProvider` drops the duplicate `Knowledge` interface and
uses the GraphQL fragment directly; no more hand-rolled field mapping.
- Both submit paths (form button and "Save & Leave" dialog) parse
values through `formSchema.safeParse` so trim/normalisation is
identical regardless of code path.
Co-authored-by: Cursor <cursoragent@cursor.com>
Extract the previously monolithic knowledge page into focused modules under
features/knowledges/ to match the resources/flows convention:
- knowledge-form: schema, helpers and RHF wiring
- knowledge-form-layout: desktop split / mobile stacked layouts
- knowledge-form-controls: meta fields and content (markdown) field
- knowledge-header / knowledge-layout: shared header and loading/not-found shell
Promote the unsaved-changes machinery to reusable primitives
(use-unsaved-changes-guard hook + unsaved-changes-dialog) so other forms
can adopt the same flow.
Tighten markdown-editor for knowledge content authoring: disable
transformPastedText (a leading "- " or "1. " no longer silently turns a
plain paste into a list/blockquote) and reserve the editor's bounding box
during tiptap initialization to avoid layout jumps on mount.
Co-authored-by: Cursor <cursoragent@cursor.com>
On the knowledge edit page the Save button was enabled immediately
after load — and the toolbar's Undo button along with it — even though
the user had not edited anything. Two distinct mount-time noises were
leaking into RHF and the UndoRedo plugin.
1. tiptap-markdown re-serializes the initial content during view
construction (whitespace around fenced code blocks, hard-break
markers, etc.) and fires onUpdate with the normalized markdown.
Forwarding this echo to field.onChange flips RHF's isDirty.
Defer onUpdate forwarding via isInitializedRef set inside onCreate
and use the editor's own serialized markdown as the echo baseline.
2. Construction-time transactions from trailingNode and the mount-time
setContent land in the UndoRedo plugin's event stack. PM's
history() uses a singleton PluginKey, so state.reconfigure({plugins})
carries the old state over; reset the stack by rebuilding the entire
EditorState instead, then dispatch an empty addToHistory:false
transaction to wake tiptap-react's subscription so the toolbar
re-renders. Only reset on initial mount and on external value sync
so user edits are not erased.
Also dedupe knowledge.tsx Create/Update payload projection into a
shared formValuesToBasePayload helper and rename its parameter from
v to values per code-style conventions.
Co-authored-by: Cursor <cursoragent@cursor.com>
- Introduced a new `docType` field in the `UpdateKnowledgeDocumentInput` to manage document type changes.
- Updated the `doUpdate` method to clear subtype fields (GuideType, AnswerType, CodeLang) when the document type changes.
- Added comprehensive tests for various document type transitions to ensure correct behavior and state preservation.
- Updated GraphQL schema and generated models to accommodate the new `docType` field.
Build a small Autocomplete family on top of cmdk and Radix Popover so the
Pull dialog's container path field gets fuzzy-filtered suggestions from
paths the user has already touched (cached files, current listing,
ancestors), while still letting them type arbitrary paths. Renders inline
(no portal) to survive Radix Dialog's body scroll-lock, and delegates the
DOM input to the project Input component via Radix Slot (asChild) so cmdk
keeps the value sync and combobox ARIA without duplicating styles.
A single useCommandState selector returning a primitive hasActiveMatch
boolean keeps the per-keystroke re-render count down to one.
Drive-by: pluralize the "Upload file" dropdown item in FlowForm to "Upload
files" to match the input's multiple attribute.
Co-authored-by: Cursor <cursoragent@cursor.com>
Adds a chevron toggle next to the "Name" header that flips every
directory in the full tree (filter-independent). Uses the existing
overrides map via a new `setExpansion(paths, isExpanded)` bulk helper
on `useFileManagerExpansion`, so a single gesture wins over the
auto-expand-on-search behavior. Skeleton header stays in lock-step.
Co-authored-by: Cursor <cursoragent@cursor.com>
The old helpers mutated the Set passed in, but the type signature
(`Set<string>`) did not communicate that — only the JSDoc did. Every
existing caller already cloned `prev` before calling, so the migration
to pure `(prev, paths) => new Set` variants is zero-cost and removes a
foot-gun. `toggleSubtreeOnSet` and `computeRowClickSelection` now
compose the pure helpers directly instead of clone-then-mutate.
Co-authored-by: Cursor <cursoragent@cursor.com>
Document the ref-based loop between performSave, onSaveFromDialog, and
useUnsavedChangesGuard so a cold reader can answer "why is the ref
declared after performSave?" without re-tracing the whole component.
Co-authored-by: Cursor <cursoragent@cursor.com>
Lock in the contract that directories collapse to size 0 in compareSizes.
Invisible while folders-first is on, but user-visible (and easy to regress)
once the Resources page lets the user disable that partition.
Co-authored-by: Cursor <cursoragent@cursor.com>
App shell:
- Switch from BrowserRouter+Routes to createBrowserRouter so pages can use
data-router-only APIs (useBlocker). Route definitions live at module scope.
FileManager:
- Sortable headers (name/size/modified) with three-state cycle, optional
per-column sortability, controlled / uncontrolled+localStorage modes via
the new useFileManagerSorting hook.
- isFoldersFirst toggle and recursive sortFileManagerTree pure reducer.
- formatModifiedAbsolute alongside the relative formatter; hosts switch via
the new Resources "Relative dates" toggle.
- Mirror hover highlight while a row's context/dropdown menu is open so the
user knows which row the menu belongs to.
- Guard row pointerdown so a touch long-press no longer stacks the row menu
on top of the empty-area menu.
Knowledge edit page:
- Decompose into focused subcomponents (header, intro, meta fields, content,
desktop/mobile body, leave dialog).
- Targeted useWatch on docType so the markdown editor no longer re-renders
meta fields on every keystroke.
- New useUnsavedChangesGuard hook encapsulates useBlocker, beforeunload and
the "Save & Leave" dialog; supports skipNextBlock for post-save navigation.
MarkdownEditor:
- Suppress echo updates from tiptap-markdown's re-serializer so RHF's
isDirty flag stays accurate.
Shared utilities:
- lib/local-storage.ts (zod-validated getStorageItem/setStorageItem) used by
both table-storage.ts and the new file-manager-storage.ts.
- lib/table-sort.ts#cycleColumnSort shared between Knowledges and Templates.
- hooks/use-latest-ref.ts replaces five useRef+useEffect pairs in FileManager.
DataTable:
- Filter input upgraded to InputGroup with search icon and clear button.
- Extract DataTableFilter subcomponent to drop the inline IIFE.
Resources page:
- Per-page persisted view options (folders-first, relative dates, optional
size/modified columns) extracted into a typed ResourcesViewOptions shape
with a centralized defaultViewOptions and a single loadViewOptions reader.
- Promote upload / new-folder buttons to the page header.
Misc:
- Replace MoreHorizontal / MoreVertical icons with Ellipsis for visual
consistency.
Co-authored-by: Cursor <cursoragent@cursor.com>
- Reword PR #268 references to talk about review feedback rather
than the PR being rejected.
- Clarify host.docker.internal availability: not universally provided
by the core compose stack; Docker Desktop typically resolves it,
while Linux/operator-managed compose stacks may need an explicit
extra_hosts: host.docker.internal:host-gateway entry or another
controlled endpoint.
- Make the safe initial Burp example unambiguously read-only: drop
start_active_scan from the illustrative allowlist and call out
that active capabilities belong to a later, explicitly gated
milestone with scope and approval controls.
- Rephrase the awkward 'PentAGI must not be inferred...' sentence
for clarity.
Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
- Introduced "/resources" and "/knowledges" routes to the frontendRoutes array in the router configuration, expanding the application's routing capabilities.
- Removed the requirement for the "destination" field in MoveResourceRequest, allowing it to be an empty string, which signifies moving to the root directory.
- Updated related documentation in swagger.json, swagger.yaml, and docs.go to reflect the new behavior.
- Adjusted the MoveResource function to handle cases where the destination is empty, ensuring proper path sanitization and resource movement semantics.
- Enhanced test cases to cover scenarios involving moving resources to the root directory and handling conflicts appropriately.
- Allow POST /flows/0/assistants/ to create a new flow together with the assistant, mirroring the existing GraphQL createAssistant(flowID: 0) behavior
- Require both assistants.create and flows.create permissions when flowID=0
- Add explicit flow ownership check for non-zero flowID using flows.admin scope
- Load flow data in the response by fetching it via assistant.FlowID after creation, ensuring AssistantFlow is fully populated in all cases
- replace plain textarea with a tiptap-based markdown editor (StarterKit, tiptap-markdown, placeholder) and a basic formatting toolbar so authors can edit knowledge content with rich formatting while keeping markdown as the storage format for embeddings
- introduce a reusable MarkdownEditor shared component and a tiptap Storage type augmentation
- move the save action from the input addon into the page header on the right
- give each desktop resizable panel its own internal scroll so long meta or content no longer makes the whole page scroll
Co-authored-by: Cursor <cursoragent@cursor.com>
Wire up KnowledgesProvider with Apollo subscriptions and cache policies,
add /knowledges routes and sidebar entry, plus minor formatting cleanups
across file-manager, upload-validation and resources upload helpers.
Co-authored-by: Cursor <cursoragent@cursor.com>
- File manager core:
- Chevron click on folder rows now drills in via `onOpenDirectory`
(when set), matching the existing double-click / Enter semantics.
Consumers that don't wire the prop keep the legacy expand/collapse
behaviour, so flow-files / resources trees stay unchanged.
- Bulk actions bar wraps and collapses to icon-only buttons (Cancel
included) on small viewports so the bar stays usable on mobile.
- Fix tri-state subtree toggle requiring two clicks when the
directory's own path was never in the selection (e.g. user ticked
children one-by-one). \`toggleSubtreeOnSet\` now accepts an optional
\`rootPath\` and ignores it for the "all selected?" check, mirroring
what \`computeDirSelectionState\` shows on the visible checkbox.
Covered by new regression tests in \`file-manager-utils.test.ts\`.
- Built-in icons swapped: copy-path uses \`ClipboardCopy\` instead of
\`Copy\`; bulk \"Save as resources\" uses \`FolderOutput\` instead of
\`BookmarkPlus\`.
- Pull dialog: flatten the container listing (\`name\` as \`path\`,
absolute path in \`id\`) so the chevron / double-click drill into
real subfolders instead of toggling a synthetic \`work/\` wrapper that
has no meaningful navigation target. Selection is mapped back to
absolute paths via a name → absolute lookup before pulling.
- Resources page: drop the focus-derived \`currentDir\` plumbing —
toolbar mkdir / upload always target the library root, row context
menu loses \"Upload files here\" and renames \"New folder here\" to
\"New folder\". Page wraps in \`h-[calc(100dvh-3rem)]\` so the bulk
bar stays inside the viewport. Tooltips simplified accordingly.
- Flow files toolbar: replace the standalone Info icon with rich
per-button tooltips that explain where each gesture lands
(/work/uploads, /work/resources, separate Container snapshot area);
upload button uses the standard \`Upload\` glyph.
- Attach resources dialog: switch the ad-hoc footer to a proper
\`DialogFooter\` with responsive layout, tighten the dialog title.
- \`Dialog\` / \`Sheet\` footers always apply the inter-button gap,
not only at the \`sm+\` breakpoint.
Co-authored-by: Cursor <cursoragent@cursor.com>
Two cleanups closing the remaining P2/P3 gaps in the flow-files / resources
upload + delete paths.
A.4 — unify upload-batch validation
- New shared validator at `frontend/src/lib/upload-validation.ts` (with
tests) exposing `validateUploadBatch(files, limits)`. Mirrors the
per-file / per-batch / empty-file rules enforced by both backends
(`pkg/resources/resources.go`, `pkg/flowfiles/files.go`).
- `useResourcesUpload` migrated off its private validator onto the shared
helper; behaviour and toast strings unchanged.
- `useFlowFilesUpload` now runs the same preflight before constructing
the FormData. Hitting any of the 300 MB / 1000 files / 2 GB / 0-byte
rules surfaces a synchronous toast instead of a network round-trip
followed by a generic 413.
- Added `FLOW_FILES_MAX_FILE_SIZE_MB`, `FLOW_FILES_MAX_UPLOAD_TOTAL_SIZE_MB`
and `FLOW_FILES_MAX_UPLOAD_FILES_PER_REQUEST` to flow-files-constants
alongside the existing resources constants — kept as a separate set so
the two backends can diverge later without touching unrelated call
sites.
C.2 — drop redundant refetchFiles() after flow-file mutations
- The backend already publishes per-file flowFileAdded / flowFileDeleted
events (with directory expansion on delete), `lib/apollo.ts` already
maps them through the universal subscriptionCacheLink, and
`useFlowFilesRealtime` already wires the three subscriptions. Only the
imperative `await refetchFiles()` in upload/delete plus the
`onSuccess={refetchFiles}` props on pull/attach dialogs were left over
from the pre-subscription era.
- Dropped `refetchFiles` from `useFlowFilesUpload` and `useFlowFilesDelete`
param types and removed the matching `await` calls. Added optional
`onAfterDelete` to the delete hook (mirrors `useResourcesDelete`) for
callers that want a UI hook without driving a refetch.
- Made `onSuccess` optional on `FlowFilesPullDialog` and
`FlowFilesAttachResourcesDialog`; removed the `onSuccess={refetchFiles}`
passthroughs in `flow-files.tsx`. The pull dialog's internal
`refetchListing` over the container listing (a separate hook) is kept.
Verified: vitest 140/140, eslint clean on touched files, tsc shows only
the same pre-existing errors as before this change (`User.ts`/`user.ts`
casing; `single possibly undefined` in unrelated delete branches).
Co-authored-by: Cursor <cursoragent@cursor.com>
- Send `sources[]` (was single `source`) to /resources/copy,
/resources/move and /files/to-resources so multi-select operations
execute in one DB transaction; replace the per-feature 409 aggregation
state and the now-unused `resources-conflict-dialog` with the shared
`useOverwriteAction` workflow returning `OverwriteOutcome`.
- Extend `FileManager` with `emptyAreaActions` (right-click context menu
over the tree's empty area), `appliesToFiles` filter (companion to
`appliesToDirs`), `onActiveRowChange` focus reporting and row-level
external-file drop (`onExternalFileDrop`).
- `useFilesDragAndDrop`: capture-phase `onDropCapture` resets the
internal counter / `isDragging` flag before any descendant claims the
drop with `stopPropagation`, fixing the page-level upload overlay
staying stuck after a row-level drop.
- `useResourcesUpload` gains `defaultDir` (read via ref so `uploadFiles`
stays reference-stable) and `openFilePickerForDir` so toolbar /
sidebar / CTA pickers upload into the focused folder by default and
per-row "Upload here" actions can target a specific directory.
Co-authored-by: Cursor <cursoragent@cursor.com>
Replace the single `onBulkDelete` prop with a generic `bulkActions` array so the
host owns which gestures appear in the footer bar. Built-in helpers (`bulkDeleteAction`,
`bulkCopyPathsAction`, `bulkMoveAction`, `bulkCopyAction`, `bulkPromoteAction`)
match the row-action pattern; each entry supports inline button or trailing
overflow menu, optional confirm dialog, isDisabled / isHidden predicates, and
receives the deduped FileNode[]. The bar also surfaces a cumulative size
summary alongside the item count.
Fix Shift+click range selection so it matches user expectations and the rest
of the file-manager's folder semantics:
- Range clicks are now ADDITIVE: the visible-order slice is unioned onto the
previous selection instead of replacing it, so Cmd-clicked picks, earlier
shift-ranges, and explicitly clicked folder subtrees survive a follow-up
Shift+click.
- Folders inside the slice expand to their full subtree via `dirSubtreePaths`,
mirroring the contract of a plain folder click. Without this, a Shift+click
across collapsed sibling folders left the folder paths in `selectedPaths`
but rendered their tri-state checkboxes as unchecked because no descendants
had been added to the selection.
- Anchor preservation across chained Shift+clicks is unchanged; toggle/single
still move the anchor.
Migrate `flow-files`, `resources`, and the move/copy/promote dialogs to the
new `bulkActions` API.
Tests: 131 passing — covers reverse direction, expanded vs. collapsed folders,
nested folders, mixed file/folder anchors, empty folders in range, omitted
`dirSubtreePaths` (tree-less callers), anchor=null and off-screen anchor
fallbacks, chained shift-clicks accumulating subtrees, toggle + shift-click
combinations, idempotent same-row range clicks, and the additive contract's
explicit divergence from Finder/Explorer (range never shrinks the selection).
Co-authored-by: Cursor <cursoragent@cursor.com>
- Introduced new fields `version` and `isDevelopMode` in the Settings model to provide application versioning and development mode status.
- Updated GraphQL schema and resolvers to support the new fields, ensuring they are accessible via the Settings query.
- Enhanced Swagger documentation to reflect the changes in the Settings API endpoint.
- Added necessary validation and response handling for the new fields in the Settings service.
Address Copilot review feedback on PR #306:
- Lifecycle diagram: show running <-> waiting (waiting is a paused state that resumes to running when user input arrives) and document that both running and waiting can reach the terminal statuses finished or failed.
- Replace overloaded 'finished' wording with explicit 'terminal' semantics throughout. finished and failed remain distinct terminal statuses; the queue and webhook layers treat both as terminal.
- Align webhook event names with status terminology: flow.finished for success, flow.failed for failure. Update payload example accordingly and note the failed-flow shape.
Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
Address Copilot review feedback on PR #305: the 'Current Limitations' bullet for the Graphiti integration mixed PentAGI's user-facing .env variables with the container env vars defined in docker-compose-graphiti.yml.
Reword both README.md and backend/docs/config.md to lead with the user-facing OPEN_AI_KEY and OPEN_AI_SERVER_URL .env variables and explicitly note that docker-compose-graphiti.yml maps them into the bundled vxcontrol/graphiti container as OPENAI_API_KEY and OPENAI_BASE_URL. Operators set the .env variables; the container variables are an implementation detail.
Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
Address Copilot review feedback on PR #304:
- Clarify the UserFiles template variable produces a <task_files> XML block with <uploads>/<resources> nested sections (matches flowfiles.FileListingForPrompt output).
- Distinguish that uploads/resources mirror to /work/uploads/ and /work/resources/, while container snapshots can originate from arbitrary container paths and are cached only under container/ on the flow side.
- Note that the 255 filename limit is enforced by len(name) <= 255, i.e. byte-length, so it is roughly 255 ASCII characters.
Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
Proposes a design direction for native flow concurrency control and
completion notifications. The RFC follows the maintainer's relocated
proposal pattern at examples/proposals/<topic>.md and explicitly
builds on the lessons from PR #268 (rejected because the in-memory
queue was hidden lifecycle state).
The RFC covers:
- Goals limited to capping concurrent flows, persisting queued flows
as first-class lifecycle, replacing external polling with at-least-
once webhooks, and preserving the existing createFlow contract.
- Non-Goals that explicitly forbid hidden in-memory queues, multi-
tenant scheduling, generic event bus features, and changing the
meaning of 'finished' for tasks/subtasks/toolcalls.
- Design Principles for persistence, visibility, manageability,
explicit promotion, clear finished semantics, and at-least-once
delivery.
- A proposed concurrency model with a new persisted 'queued' status,
a single MAX_CONCURRENT_FLOWS knob, an explicit promoter, and
full UI/API visibility plus user cancellation.
- A proposed completion webhook model with per-flow and global URLs,
HMAC-SHA256 signatures, persisted deliveries, bounded retries,
and SSRF mitigations.
- Storage and API surface sketches that do not commit to a final
schema.
- Open Questions covering per-user limits, blocking semantics on
createFlow, signature alignment with the issue #235 receipt
direction, and behavior of resources/uploads against queued flows.
- A Suggested First Milestone that lands the queue end-to-end before
webhooks, to keep PR sizes reviewable.
This is documentation only. No runtime code, schema, GraphQL, REST,
or UI behavior changes here.
Refs #298
Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
The Graphiti container shipped with docker-compose-graphiti.yml only
takes OPENAI_API_KEY and OPEN_AI_SERVER_URL for entity extraction.
PentAGI configures many other LLM providers (Anthropic, Google AI,
AWS Bedrock, DeepSeek, GLM, Kimi, Qwen) for the main flow, but those
credentials are not consumed by Graphiti today. Until that changes,
operators need to plan around an OpenAI-compatible endpoint just for
the knowledge graph.
This commit makes the limitation visible in two surfaces without
changing runtime behavior:
- README.md: Adds a beta callout at the top of the Knowledge Graph
Integration section and a new 'Current Limitations' subsection
covering provider scope, fixed model, independent billing, and the
lack of an in-app graph explorer.
- backend/docs/config.md: Mirrors the beta callout under Graphiti
Knowledge Graph Settings and adds a 'Current Limitations (Beta)'
subsection with the same constraints, so config-focused readers
see the same message.
Both notes explicitly point at the simple fallback: leave
GRAPHITI_ENABLED=false if the deployment cannot reach an
OpenAI-compatible endpoint.
Refs #187
Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
Add a How-to subsection that describes the Files tab on a flow page
without restating implementation details. The new section covers:
- The three file sources surfaced in the UI (uploads, resources,
container snapshots) with their exact action labels.
- The on-host layout under {dataDir}/flow-{id}-data/ and the
corresponding container paths /work/uploads and /work/resources.
- Per-file actions (Download, Copy path, Save as resource, Delete)
and the Pull action's disabled state when the container is not
running.
- Automatic injection of uploaded files and attached resources into
agent system prompts via the <UserFiles> block, so users understand
how the assistant sees their files.
- Current limits (300 MB / 1000 files / 2 GB / 255-char names) and
current limitations, including that flow deletion does not yet
archive or remove the flow data directory on disk.
This is a documentation-only change and does not introduce or change
runtime behavior.
Refs #193
Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
Address two reviewer concerns on the issue #300 follow-up:
* Replace the `DumpTemplates()` -> `json.Unmarshal` round-trip in
buildUserPrompter with a new `templates.LoadDefaultPromptsMap()`
helper that returns the embedded defaults as a `PromptsMap`
directly. `defaultPrompter.DumpTemplates()` now delegates to the
same helper, so the JSON output for that API is unchanged.
* Add an optional `prompter` field to `assistantWorkerCtx`. When
set, `LoadAssistantWorker` reuses it instead of re-querying
`GetUserPrompts` and re-merging defaults. `LoadFlowWorker`
populates it once per flow load so multi-assistant flows pay the
DB+merge cost a single time.
Tests updated to match the new pure-merge `buildUserPrompter`
signature; behavior for users with no overrides is unchanged.
Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
Address review on PR #303.
- helpers.go: remove the concrete model examples (llama3.1, qwen2.5, mistral-nemo) from the Ollama tools-unsupported hint. PentAGI does not verify Ollama model capabilities from upstream metadata, so a hard-coded list of supposedly tool-capable tags is risky and ages poorly. The hint now points users to select an Ollama model whose own metadata advertises tool/function calling support.
- helpers.go: rewrite the comment and error wording so it is no longer flow-only. The helper is shared by NewFlowProvider and NewAssistantProvider, so the message now refers to tool execution in flows and assistant sessions, and the doc-comment notes that wording must stay context-neutral.
- helpers_test.go: tighten TestWrapToolCallIDTemplateError to match the new wording, ban the previous concrete model tags, and ban flow-only language ('flow execution', 'flow creation'). The test still verifies that the original underlying error is wrapped via errors.Is.
Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
## Summary
Surface an actionable hint when an Ollama model that does not support
tool/function calling is selected for a flow or assistant session, so
users do not have to parse a five-wrap-deep "failed to determine tool
call ID template" stack trace to figure out why flow creation fails.
## Problem
A user on an Ollama deployment of `gemma3:27b-it-q4_K_M` reports that
the Provider/LLM test passes the basic completion checks but flow
creation fails with:
failed to create flow worker: failed to get flow provider: failed
to determine tool call ID template: failed to collect tool call ID
samples: all sample collection attempts failed: failed to call LLM:
400 Bad Request: registry.ollama.ai/library/gemma3:27b-it-q4_K_M
does not support tools
The underlying signal "does not support tools" is emitted by the
Ollama API itself; PentAGI buries it five wraps deep, so the user is
left guessing whether the issue is configuration, networking, or
something internal to PentAGI.
## Solution
Add an unexported helper `wrapToolCallIDTemplateError` in
`pkg/providers/helpers.go` that detects the upstream "does not support
tools" substring and prepends a one-sentence guidance message naming
the constraint and a few known-good Ollama tags
(`llama3.1`, `qwen2.5`, `mistral-nemo`). All other errors keep the
existing wording. The original error is preserved via `%w` so log
spans, langfuse traces, and any future `errors.Is/As` callers continue
to work.
Both call sites in `pkg/providers/providers.go`
(`NewFlowProvider`, `NewAssistantProvider`) now route through the
helper.
No schema, API, or DB changes. No new lifecycle state. No background
work. The behavior change is the wording of one error string in one
upstream-defined failure case.
## User Impact
- Users who pick an Ollama model without tool support get a clear,
actionable error during flow / assistant creation instead of a deep
stack trace.
- Users on tool-capable models (Anthropic, OpenAI, Bedrock, and
tool-capable Ollama tags) see no behavioral or message change.
- No restart, migration, or configuration step required.
## Test Plan
- New table-driven test `TestWrapToolCallIDTemplateError` covers:
- nil error -> nil
- upstream "does not support tools" chain (matching the real five-
wrap shape) -> actionable message + `errors.Is` round-trips to the
original error
- generic non-tools error -> existing wrap text preserved, no
new guidance appended
- `go test ./pkg/providers/...` passes locally.
- `go build ./...` and `go vet ./pkg/providers/...` clean.
Closes#280
Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
Custom prompts saved via the Settings -> Prompts UI are persisted to the
database, but every assistant and flow session creation path was using
templates.NewDefaultPrompter() with a leftover TODO, so user overrides
never reached the agents and Langfuse traces always showed the defaults.
Add a controller-side helper that loads the user's saved prompts and
overlays them on the compiled defaults. Prompt types the user has not
customized continue to use the defaults; an empty body row is treated
as no override (the UI uses delete to reset). A database error fails
session creation explicitly instead of silently falling back.
Wire the helper into the four affected call sites in NewAssistantWorker,
LoadAssistantWorker, NewFlowWorker, and LoadFlowWorker.
Closes#300
Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
- Add Sources []string to MoveResourceRequest, CopyResourceRequest and AddResourceFromFlowRequest; merged with Source, deduplicated; multi-source uses destination as base dir and runs in a single atomic DB transaction
- Fix MoveResource response to return Added + Updated (not Updated only) so Apollo cache receives new parent directory entries alongside moved items
- Add missing errResourceNotFound case in CopyResource (was 500 instead of 404)
- Cover all new behaviour with table-driven tests (basename conflict, force overwrite, missing source, empty input, dir-into-itself guard, etc.)
- GraphQL/REST CRUD + semantic search for knowledge documents
- KnowledgeStore with admin/user-scoped filtering, re-embedding on update
- Real-time subscriptions (created/updated/deleted) per user and admin
- user_id tracking in all agent-stored documents (guide/answer/code/memory)
- sqlc queries, goose migrations, privilege grants, user_id backfill
- Memory cleanup on flow deletion; stale orphan purge via migration
- Unit tests for all KnowledgeStore operations including security cases
- Frontend GraphQL schema and TypeScript types regenerated
- Added `paths[]` query/body parameter to DeleteFlowFile, DownloadFlowFile,
GetFlowContainerFiles, PullFlowFiles, ListResources, DeleteResource, and
DownloadResource; single `path` parameter retained for backward compatibility.
- Introduced `DeduplicatePaths` in flowfiles package with coverage-based
deduplication (parent covers children), path normalization, and traversal safety.
- Added `ZipRelativePaths` to create ZIP archives from cache-relative paths,
sharing `zipWriteFile` helper with refactored `ZipDirectory`.
- Switched all ZIP and single-file responses to buffered `DataFromReader` with
explicit `Content-Length`, fixing Swagger UI download rendering.
- Expanded response payloads: delete and pull operations now enumerate all
affected nested files; list responses include ancestor directories for tree
completeness.
- Extended test coverage across flowfiles, flow_files, and resources packages
with batch, deduplication, atomicity, Docker exec, and security scenarios.
- Implemented `SanitizeJSONControlChars` to escape literal control characters in JSON string values, ensuring compliance with the JSON specification.
- Enhanced `SanitizeToolCallArguments` method to apply sanitization across tool call arguments in the chain.
- Added comprehensive tests for both sanitization functions to validate behavior with various input scenarios.
- Updated the logic in `determineRecentSectionsToKeep` to clamp the lower bound of the recent sections to keep, ensuring it does not exceed the available sections. This prevents potential out-of-range errors when `keepQASections` is greater than the total number of sections.
- Updated `getHTML` and `getMD` methods to return warnings for small content instead of errors.
- Implemented checks for binary URLs, returning descriptive errors when such URLs are encountered.
- Added new tests to validate the updated behavior for small and empty content handling.
- Added TryLock mechanism to avoid deadlock situations when reading from the channel while the mutex is held.
- Enhanced timer handling to reset when the mutex is not available, ensuring continuous operation of the stream.
- Added new provider configurations for vLLM Qwen 3.6 in both thinking and non-thinking modes.
- Updated the Dockerfile to include the new configuration files for vLLM Qwen 3.6 and ensure proper setup for deployment.
- Folder rows now surface a tri-state checkbox derived from descendant selection;
clicking / shift-clicking / toggling a folder flips the entire subtree in one
gesture, including descendants of a collapsed folder.
- Files get a new onOpen prop, fired on double-click and Enter; directories keep
expanding/collapsing. The resources page wires it to the existing download flow.
- Drop on a file row forwards to its parent folder so the whole folder acts as a
single drop zone (Finder/Explorer semantics), with a shared drag-enter counter
so highlight stays stable when moving the cursor between sibling rows.
- Extract pure data layer into useFileManagerData and pure selection reducers
(computeRowClickSelection / computeToggleSelection / computeToggleSelectAll /
computeDirSelectionState) into file-manager-utils; bundle per-tree row props
into display / handlers so memoized rows stay reference-stable across parent
re-renders, keyboard expansion, and selection changes.
Co-authored-by: Cursor <cursoragent@cursor.com>
- Updated resource ID handling to ensure consistent string coercion for numeric IDs across components.
- Enhanced sorting of resources in the FlowForm to use alphabetical order based on path.
- Improved resource attachment logic in the FlowFilesAttachResourcesDialog to avoid deduplication of descendants.
- Introduced utility functions for converting REST resource entries to a consistent format for Apollo cache.
- Adjusted upload handling to ensure proper type consistency between REST and GraphQL responses.
- Refactored promote functionality to align with updated resource ID handling and improve clarity in parameters.
- Adjusted descriptions in API documentation to clarify paths for uploads, resources, and containers.
- Updated data models to use consistent naming conventions (e.g., `isDir` to `is_dir`, `modifiedAt` to `modified_at`).
- Changed resource ID types from string to uint64 for better consistency across the application.
- Enhanced flow file upload functionality to support batch processing of resource files.
- Removed deprecated code related to resource entry responses in tests.
- Replace resources feature mocks with real GraphQL + REST integration
(Apollo subscriptions-backed cache, dedicated hooks for search, upload,
copy, move, mkdir, delete, plus conflict / mkdir / copy / move dialogs
and a shared FileDropZone UI component).
- Let flows attach user resources on creation and in chat messages:
FlowForm exposes resourceIds as a form field with a multi-select
dropdown (file/folder icons), wired through createFlow, createAssistant,
putUserInput and callAssistant mutations.
- Add attach-resources and save-as-resource (promote) dialogs to the
flow files page; unify drag-and-drop via a shared
hooks/use-files-drag-and-drop.
- Harden file manager: align skeleton layout (grid + column config) with
real rows, extract use-file-manager-dnd, add group selection state and
tree-node accessibility fixes.
- Normalize numeric id/userId from REST /resources/ responses to strings
so GraphQL ID-typed consumers (zod-validated resource picker) work.
Marked with TODO(backend) for removal once the REST endpoint matches
the GraphQL ID scalar.
- Ignore *.tsbuildinfo artifacts.
Made-with: Cursor
Drops `components/ai/file-tree.tsx` and `components/blocks/{crud,skeleton}/*`
reference snippets that were never imported anywhere; the real
file manager lives under `components/file-manager/` and is the only
implementation in use.
Made-with: Cursor
- split monolithic FileManager into FileManagerTreeNode, FileManagerBulkActionsBar, and useFileManagerKeyboardNavigation
- group FileManagerProps columns/search into nested configs and rename visibility booleans from show* to is*Visible per project convention
- replace abbreviations (idx, i, Sep, Item) with full names across components, hooks, and tests
- add ARIA tree-pattern attributes (aria-level, aria-posinset, aria-setsize, aria-multiselectable) and fix aria-hidden hiding the Select-all checkbox
- add labels.formatModified to localize the date column
- make walkTree strictly pure by hiding its internal accumulator
- move side effects out of the setState updater in useFileManagerSelection
- drop redundant stopPropagation in favor of the data-fm-skip-row-click marker
Made-with: Cursor
- vendor the shadcn ai/file-tree primitive (recursive collapsible tree with shared expand/select context) for future AI chat surfaces
- vendor the shadcn crud-file-manager and skeleton-file-manager demo blocks as design references; not wired into any route yet
Made-with: Cursor
- handleConfirm now accepts () => Promise<void> | void; the dialog awaits the promise before closing
- show a Loader2 spinner on the confirm button while the handler is in flight, and disable both confirm and cancel
- block onOpenChange and outside-clicks while processing so the dialog can't be dismissed mid-action
- caller no longer needs to manage its own loading state for confirm-then-async flows
Made-with: Cursor
- add ApiResponse<T> / ApiSuccessResponse<T> / ApiErrorResponse / ApiHttpError types describing the backend protocol
- expose a typed api wrapper with helper methods (api.get / api.post / api.put / api.delete) that returns ApiResponse<T> directly and accepts per-call AxiosRequestConfig
- add unwrapApiResponse(...) and getApiErrorMessage(...) helpers so callers no longer reimplement success/error branching
- set a sensible default request timeout (30s) on the shared axios instance; long uploads still opt out via { timeout: 0 }
- migrate user-provider and password-change-form from the raw axios instance to the new typed api helpers, dropping their bespoke error-shape interfaces
Made-with: Cursor
- replace the inline file tree implementation in flow-files with the new FileManager component
- compose row actions via factory helpers (downloadAction / copyPathAction / deleteAction) instead of bespoke menus
- delegate search highlighting, expand/collapse, multi-select and bulk delete to the shared component; the page now only owns upload, drag-and-drop, pull-from-container and per-file delete confirmation
- switch to the typed axios helpers (api / unwrapApiResponse / getApiErrorMessage) for upload, pull and delete calls
Made-with: Cursor
- introduce src/components/file-manager with tree rendering, search highlighting, multi-select (single / toggle / shift-range), keyboard navigation (arrows, Home/End, Space, Cmd+A, Esc) and bulk delete
- expose unified actions[] API with downloadAction / copyPathAction / deleteAction factory helpers instead of separate built-in props
- split orchestration into useFileManagerExpansion and useFileManagerSelection hooks; derive expanded/selected state during render without useEffect, preserving Set identity for memo-friendly downstream
- add ARIA tree semantics (role=tree on the container, treeitem rows, roving tabindex via activeRowPath, aria-expanded/aria-selected)
- pure tree utils: O(1) folder lookup via Map, normalizeRootGroups, dedupeOverlappingPaths, findNodeByPath, plus 37 vitest unit tests
- ship shadcn checkbox primitive (depends on @radix-ui/react-checkbox) which the file manager uses for row and select-all controls
Made-with: Cursor
- Replaced ambiguous "user's language" guidance in tools/args.go with explicit engagement-log vs technical-channel markers per field, with strong English-only requirement for vector-store and search-engine queries.
- Added a unified LANGUAGE POLICY block to every agent prompt (primary_agent, assistant, pentester, coder, installer, searcher, memorist, generator, refiner, reporter, enricher), tailored per agent based on its actual tool set.
- Extended template variables and tool access (TerminalToolName, FileToolName) for coder, pentester, installer, memorist, generator, refiner, and enricher to match their runtime tool registrations.
- Fixed inverted UseAgents condition and removed misleading vector-store write references in assistant prompt; corrected MEMORY SYSTEM INTEGRATION for mode-specific tool references.
- Compressed COMPLETION REQUIREMENTS across templates and aligned closing-tool guidance with the channel mapping (engagement-log message vs technical-channel result).
Fixes#285.
Co-Authored-By: Octopus <liyuan851277048@icloud.com>
- Added table-driven scenarios for all 8 endpoints (Get/Upload/Delete/Download flow files, Pull from container, GetContainerFiles, AddResourcesToFlow, AddResourceFromFlow) covering success paths, all privilege combinations (view/upload/admin/cross-user), error responses (forbidden/not-found/conflict/invalid request), and security checks (path traversal, symlink rejection).
- Introduced reusable test infrastructure: sqlite-backed flows/user_resources schema, fakeDockerClient implementing the full docker.DockerClient interface, flowFileCaptureSubscriptions recording both FlowPublisher and ResourcePublisher events, and helpers for multipart upload bodies and container TAR fixtures.
- Added direct unit tests for shellQuote, parseFlowIDParam, cleanupPendingUploads, and flowScopeForFiles privilege matrix.
- Lifts handler coverage from 0% to 60-90% across the file and total services package coverage from 10.2% to 28.6%.
- Restructured single-case tests for List, Mkdir, Download, and CleanupOrphanBlobs into table-driven scenarios.
- Extended Upload, Delete, Copy, and Move scenarios with admin, forbidden, malformed JSON, invalid path, missing source, and trailing-slash hint cases.
- Added dedicated tests for blob deduplication on upload/copy, non-multipart bodies, orphan blob preservation on rollback, and direct deleteOrphanBlob coverage.
- Introduced helpers for parameterized multipart field names, custom UID context, and on-disk blob counting.
- Added methods for non-recursive directory listing and file stat operations in the Docker client.
- Implemented a new API endpoint to retrieve files from a running container's directory.
- Updated documentation to reflect new file operations and API changes.
- Introduced data structures for container file metadata and integrated them into the flow file service.
- Enhanced flow file management capabilities with improved synchronization between local and container file systems.
- Added new endpoints for managing flow files, including listing, uploading, and deleting files within flow workspaces.
- Introduced FlowFile model to represent file metadata.
- Enhanced GraphQL schema to support flow file operations and subscriptions for real-time updates.
- Updated API documentation to reflect new flow file functionalities.
- new get_flow_status / stop_flow / submit_flow_input / patch_flow_subtasks tools in assistant executor, backed by FlowWorker callbacks
- flowStatusTool supports 5 detail levels with verbose mode, polling for task readiness, and per-size summarization
- summarizer LRU cache (1000 entries, 4 h TTL, SHA-256 key) on flowProvider to skip redundant LLM calls
- updated assistant.tmpl with full flow management protocol: state reference, decision guide, constraints
- updated flow_execution.md with terminal timeout config, new tools, and cache
- Implemented a new SQL query to retrieve usage statistics by model and agents for a specific flow.
- Added corresponding Go types and methods to handle the new query in the database layer.
- Updated GraphQL schema to include the new ModelAgentsUsageStats type and the usageStatsByModelAgentsForFlow query.
- Enhanced frontend components to display the new usage statistics in the flow dashboard.
- Introduced Noto Sans, Noto Sans Mono, and Noto Sans SC fonts to improve text rendering in PDF reports.
- Updated report-pdf.tsx to register new fonts and handle CJK text rendering.
- Enhanced README.md to document the new fonts and their usage in the application.
- Added a custom hook to manage tooltip animation state and session tracking.
- Updated ChartTooltip component to handle first active state and session key.
- Integrated tooltip animation logic into various chart components in the DashboardAnalytics page.
- Changed default terminal tool timeout from 600 to 1200 seconds.
- Updated related documentation across .env.example, README.md, and config files to reflect the new timeout settings and their constraints.
- Enhanced descriptions in code comments and documentation to clarify timeout behavior, including clamping rules for values outside the accepted range.
* test: add unit tests for langfuse context and noop observer
Add tests for observation context put/get round-trip, nested context
override behavior, and noop observer: trace ID generation, parent
inheritance, explicit override, Shutdown, ForceFlush, and enqueue.
* test: add edge case tests for noop observer branch coverage
Add two missing branch tests: explicit ObservationID with no parent
context (verifies new trace generation), and explicit TraceID with
parent (verifies observation ID is NOT inherited when trace is explicit).
Adds conditional chain normalization in processChain to preserve reasoning cache when provider unchanged while fixing incomplete tool_calls and converting IDs when switching providers. Extends GraphQL API with modelProvider parameter for seamless provider changes without restart.
Add tests for NewClient with enabled=false, IsEnabled nil/disabled/enabled
receivers, GetTimeout nil/configured, AddMessages no-op on disabled client,
and all 7 search methods returning "graphiti is not enabled" error when
disabled. All tests are hermetic with no network dependency.
Add pg_isready healthcheck to pgvector service and update pentagi and
pgexporter depends_on to use service_healthy condition. This prevents
the application from starting before PostgreSQL is ready to accept
connections, matching the pattern used in docker-compose-langfuse.yml.
Add comprehensive unit tests for all utility functions in the langfuse
helpers package: mergeMaps, ObservationLevel, GenerationUsageUnit,
GenerationUsage, ModelParameters, GetLangchainModelParameters, trace/span
ID generation, time helpers, and pointer helpers.
- Add Name field to ProviderConfig; YAML name: key sets the provider
name shown in the UI (e.g. glm_flash)
- Add SeedDefaultProviders to ProviderController: upserts the Bedrock
provider into the DB for all existing users at startup and lazily for
new users on their first Settings page visit
- Editing the YAML and restarting PentAGI automatically propagates new
values with no UI interaction required
- Simplify to a single BEDROCK_CONFIG_PATH variable: compose uses it as
the host-side volume mount path and translates it to the fixed
container path via :+ substitution, eliminating PENTAGI_BEDROCK_CONFIG_PATH
- Fix bedrock_test.go: pass &config.Config{} to DefaultProviderConfig
after its signature was updated to accept a config argument
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Follow the same two-variable convention used for LLM_SERVER_CONFIG_PATH
and OLLAMA_SERVER_CONFIG_PATH:
- PENTAGI_BEDROCK_CONFIG_PATH: host-side path to the YAML file, mounted
into the container at /opt/pentagi/conf/bedrock.provider.yml
- BEDROCK_CONFIG_PATH: in-container path passed to the app, set to
/opt/pentagi/conf/bedrock.provider.yml when using the above
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Instead of passing BEDROCK_CONFIG_PATH through from the host env (which
required users to know the internal container path), set it directly to
the fixed mount point /opt/pentagi/conf/bedrock.provider.yml in compose.
Users now only need PENTAGI_BEDROCK_CONFIG_PATH pointing to their host
file — consistent with how PENTAGI_LLM_SERVER_CONFIG_PATH and
PENTAGI_OLLAMA_SERVER_CONFIG_PATH work.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Add BEDROCK_CONFIG_PATH to the AWS Bedrock Provider Configuration table
and the full env reference section to document the custom YAML config
path feature added in the feature branch.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Mirrors the existing LLM_SERVER_CONFIG_PATH / OLLAMA_SERVER_CONFIG_PATH
pattern so operators can supply a YAML file that overrides the built-in
embedded bedrock/config.yml without modifying source code.
Changes:
- config.go: add BedrockConfig field mapped to BEDROCK_CONFIG_PATH env var
- bedrock/bedrock.go: DefaultProviderConfig now accepts *config.Config;
reads from BedrockConfig path when set, falls back to embedded config.yml
- providers.go, cmd/ctester/main.go: pass cfg to updated DefaultProviderConfig
- docker-compose.yml: wire BEDROCK_CONFIG_PATH env var and mount
${PENTAGI_BEDROCK_CONFIG_PATH:-./glm_flash_bedrock.yml} into the container
- .env.example: document the new BEDROCK_CONFIG_PATH variable
- glm_flash_bedrock.yml: example config exporting the glm_flash DB provider
(zai.glm-4.7-flash via Bedrock) as a portable YAML file
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Add comprehensive test coverage for the schema package including
Schema validation, JSON Schema Draft 7 compilation, document validation,
database serialization, and custom Type marshaling.
Tests cover:
- Schema.Valid() with various schema types (string, object, array, etc.)
- Schema.GetValidator() compilation
- Schema.ValidateString/ValidateBytes/ValidateGo with valid and invalid docs
- Schema.Value()/Scan() database serialization round-trip
- Type.MarshalJSON() including object auto-properties and ExtProps
- Type.UnmarshalJSON() including ExtProps extraction
- Pattern, enum, and array constraint validation
- scanFromJSON helper with string, bytes, and error cases
- Introduce CONTRIBUTING.md for license compliance guidelines for developers.
- Update Dockerfile to generate license reports for frontend and backend dependencies.
- Add scripts for generating license reports and include them in the Docker build process.
- Create README.md and .gitignore files in the licenses directory for better organization.
- Update go.mod and go.sum to use the latest versions of vxcontrol dependencies.
This enhances the project's compliance with licensing requirements and improves dependency management.
? 'neither the workflow jobs API nor `results.json` could be read'
: !jobsFetched
? 'the workflow jobs API was unreachable, so this reflects `results.json` alone, which cannot distinguish a clean pass from a run killed mid-flight'
: '`results.json` could not be read, so this reflects the job conclusion alone and no test counts were checked';
const advisoryLine = mockStatus === 'unknown'
? `⚠️ **Result unconfirmed** — ${unconfirmedReason}. Check the run before merging.`
: visualDiffers
? '⚠️ **Visual snapshots differ** — advisory only, does not block merge. Download the `e2e-visual-diffs` artifact to compare expected / actual / diff (a missing baseline uploads actual only).'
echo "::error::e2e-visual container ships Playwright $container but @playwright/test is $pkg — bump the container tag to v$pkg-noble and regenerate baselines"
exit 1
fi
- name:Install pnpm
uses:pnpm/action-setup@v4
with:
package_json_file:frontend/package.json
# The dist must be built with the pinned Node, not whatever the
# Playwright container ships — local baselines are built under .nvmrc
# and pixel-stability assumes identically built bundles.
- name:Set up Node.js
uses:actions/setup-node@v6
with:
node-version-file:frontend/.nvmrc
- name:Install dependencies
working-directory:frontend
run:pnpm install --frozen-lockfile
- name:Build
working-directory:frontend
run:pnpm run build
- name:Run visual snapshots
id:snapshots
working-directory:frontend
run:E2E_VISUAL=1 E2E_VISUAL_CONTAINER=1 npx playwright test -c e2e/playwright.config.ts
# The step failing is not the same signal as a snapshot differing: a webServer or build
# failure inside it also exits non-zero and still leaves results.json behind, which would
# publish the artifact and make the report say "snapshots differ". Look for the diff images.
@@ -4,21 +4,66 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Core Interaction Rules
1.**Always use English** for all interactions, responses, explanations, and questions with users.
2.**Password Complexity Requirements**: For all password-related development (registration, password reset, API token generation, etc.), the following rules must be enforced:
-Minimum 12 characters
-Must contain at least 1 uppercase letter, 1 lowercase letter, 1 number, and 1 special character
- Common weak passwords (e.g., `password`, `123456`) are prohibited
- Both backend and frontend validation must be implemented; do not rely on frontend validation alone
1.**English** for code, comments, documentation, commit messages and identifiers.
2.**Password Complexity Requirements**: For all password-related development (registration, password reset, API token generation, etc.), enforce the same policy in **both** backend and frontend — never rely on frontend validation alone. Source of truth, keep the two in sync: `backend/pkg/password/policy.go` (the API validator and the installer both call it) and `frontend/src/features/authentication/password-change-form.tsx` (zod schema). The policy:
-Length 8–72 characters (72 **bytes**, the most bcrypt will hash — a longer value fails inside `bcrypt.GenerateFromPassword`, after validation).
-A password is valid if it is **either** 16+ characters (any composition), **or** 8–15 characters containing at least 1 lowercase letter, 1 uppercase letter, 1 number, and 1 special character from `!@#$&*`.
3.**Markdown is prose, not wrapped to a width.** In a `.md` file every paragraph, list item and table row is one line, and the text is split into paragraphs where the thought changes, not where a column ends — the viewer wraps it. Hard wrapping at a fixed width belongs only to comments in code.
## Code Comments
The target: comment lines at 0–2% of a file of logic and about 18% of a file of type declarations; function bodies of hundreds of lines carry none, because the code says what it does.
**A comment earns its place only by carrying what the code cannot show**: why this decision and not the obvious one, what external constraint it works around, why the code exists at all, and — where it genuinely matters — the boundary conditions. It must help maintenance and must not cost readability.
1.**Never restate the code.** If the sentence follows from the line under it, delete it. A doc comment that only repeats an identifier's name is noise; delete it rather than reword it. A comment that repeats the `fmt.Errorf` or log message on the next line is noise too.
2.**Short and dense beats long and dense.** No filler that dilutes the point.
3.**English only.** No Russian, not even a quoted requirement.
4.**No `§`, no requirement ids like `(R37)`, no reference to a document that is not in this repository.** A planning document that is not tracked leaves every pointer into it dead. Do not just delete the token — rewrite the sentence so it stands alone, or delete the comment. "The spec says X" is not a reason; if the reason is real, state the reason. (`§` is a legitimate *string* separator in `backend/cmd/installer/wizard/models/types.go`, and in `markdown-editor-marked.ts` it is the delimiter of the anonymizer placeholder `§*Name*§` that the code reads — neither is a pointer into a document.)
5.**No archaeology.** Git holds the history. Delete "it used to be", "no longer", "before this", "now that X arrives", "was an overgeneralisation". Keep the invariant the story was there to protect. This applies to test *names* as well as test comments.
6.**No meta-commentary** about why the enum has five members rather than four, and no narrative padding that sets a scene or argues with an imagined reviewer.
7.**Rationale lives in one place** — the production code. A `_test.go` gets at most one line saying what a case pins down, and only when the test name does not already say it.
8.**When you change a comment, verify it against the code**, including that the case it describes is still reachable where it sits. A shorter comment that is wrong is worse than the long one.
Keep, and shorten only where it stays unambiguous: package doc comments; the contract of an exported identifier (units, ownership, zero/nil semantics, what the caller must hold); locking, ordering and fail-closed rationale; load-bearing formatting facts; workarounds for a library, protocol, database or browser quirk. Never touch `TODO`/`FIXME`, `//nolint`, `// eslint-disable`, `//go:generate`, `//go:embed`, build tags, or the swaggo `// @...` annotations in `pkg/server/services/` — they are machine-read, not prose.
Two kinds of comment here are machine-read even though they look like prose: the triple-quoted descriptions in `schema.graphqls`, which reach `models_gen.go`, the frontend types and every API consumer; and the comment above a `-- name:` line in `backend/sqlc/models/*.sql`, which is copied verbatim into `pkg/database/*.sql.go`. Both need regeneration after an edit.
### The GraphQL schema
`backend/pkg/graph/schema.graphqls` is a **public** artifact: introspection is on by design, so every triple-quoted description in it ships to clients and bloats the spec. A `#` comment does not ship — the parser drops it, so no client sees it and regeneration leaves every output unchanged — but it is read by everyone who edits the file. The schema carries almost no prose.
**No triple-quoted descriptions anywhere.** Not on types, not on fields, not on operations, not on enum values.
**A comment on a type, when one is genuinely needed, is a single `#` line above it, with no trailing period.** It earns its place only by saying something a client cannot get from the name — for example that the bytes are served over REST and not here, or that every mutation of the shipped template is refused.
**Fields inside types and inputs are never commented.** The name and the type are the documentation; anything more belongs in `backend/docs/` or in the Go code.
**Queries, mutations and subscriptions are never commented.** Their names say what they do; if a name does not, rename it. A single `#` line may head a *group* of operations as a navigation marker, nothing more.
**Enum values are commented only where the name does not give it**, and then about what the value leads to or how the algorithm treats it — one `#` line each.
After editing the schema, regenerate: `gqlgen`, then `swag init` — the swagger document is built from the gqlgen-generated models — and then `pnpm run graphql:generate` in `frontend/`.
**Proving a comment-only change touched no code.** For anything larger than a few files, compare the comment-free token stream of each file against its previous revision rather than reading the diff: a ~30-line Go program over `go/scanner` for `.go`, and `ts.createPrinter({removeComments:true})` over `ts.createSourceFile(...)` for `.ts`/`.tsx` (the raw `ts.createScanner` returns `Unknown` inside JSX and is not a substitute). Prove the checker itself in both directions — plant a one-token change and confirm it fails, plant a comment-only change and confirm it passes — before trusting it. A dead reference inside a string literal (a `t.Errorf` format, a `describe(...)` title) is a code token and needs its own deliberate edit.
## Project Overview
**PentAGI** is an automated security testing platform powered by AI agents. It runs autonomous penetration testing workflows using a multi-agent system (Researcher, Developer, Executor agents) that coordinates LLM providers, Docker-sandboxed tool execution, and a persistent vector memory store.
**PentAGI** is an automated security testing platform powered by AI agents. A `primary_agent` drives a flow, a `generator`/`refiner` pair plans and re-plans its subtasks, and specialist agents — `pentester`, `coder`, `searcher`, `installer`, `memorist`, `adviser`, `reflector`, `enricher`, `reporter`, `summarizer`, `assistant`, `tool_call_fixer` — execute them against LLM providers, Docker-sandboxed tools and a pgvector memory store. The authoritative list of roles is the `MsgchainType` enum in `backend/pkg/database/models.go`, mirrored as `AgentType` in the GraphQL schema.
go generate ./cmd/installer/files/ # REQUIRED once per fresh clone and again after a change under
# cmd/installer/files/links or to a file linked there: fs.go,
# fs_test.go and fs/ in cmd/installer/files/ are generated and
# gitignored; the installer tests fail without them
go build -trimpath -o pentagi ./cmd/pentagi # Quick compile; the binary reports version "ce"
go test ./... # Default test tier (see Testing)
golangci-lint run --timeout=5m # Lint — config backend/.golangci.yml (v2 schema); CI pins v2.12.2
```
A binary whose reported version matters needs the ldflags CI passes: `-ldflags "-X pentagi/pkg/version.PackageVer=<ver> -X pentagi/pkg/version.PackageRev=<short-sha>"`.
### Frontend (run from `frontend/`)
```bash
npm ci # Install dependencies
npm run dev # Dev server on http://localhost:8000
npm run build # Production build
npm run lint# ESLint check
npm run lint:fix# ESLint auto-fix
npm run prettier # Prettier check
npm run prettier:fix # Prettier auto-format
npm run test# Vitest
npm run test:coverage # Coverage report
npm run graphql:generate # Regenerate GraphQL types from schema
nvm use# Node from .nvmrc — corepack does not manage Node
corepack enable# once per Node install: activates the pnpm pinned in package.json
pnpm install
pnpm run dev# Dev server on http://localhost:8000 (VITE_PORT / VITE_HOST / VITE_USE_HTTPS override it)
pnpm run build # tsc -b && vite build
pnpm run typescript # Typecheck only. Use THIS: the root tsconfig is `files: []`, so
# `tsc --noEmit -p tsconfig.json` passes without checking anything
pnpm run lint# ESLint, --max-warnings 0 over src, e2e and scripts
pnpm run prettier # Format check (prettier:fix / lint:fix to write)
pnpm run test# Vitest (test:watch, test:coverage)
pnpm run e2e # Playwright, mock tier (see Testing)
pnpm run graphql:generate # Regenerate src/graphql/types.ts
docker build -t local/pentagi:latest . # Image, version "ce"
./scripts/build-image.sh # Image stamped the way
# the pipeline stamps it
```
The full stack runs at `https://localhost:8443` when using Docker Compose. Copy `.env.example` to `.env` and fill in at minimum the database and at least one LLM provider key.
`docker-compose.e2e.yml` is not part of that stack: it is the isolated Tier-2 e2e backend, started under its own compose project (see the header of the file).
The full stack runs at `https://localhost:8443`. Copy `.env.example` to `.env` and fill in at minimum the database and one LLM provider key.
## Testing
**Backend.**`go test ./...` is not the whole suite — one tier sits behind a build tag and is invisible without it:
```bash
PENTAGI_TEST_DSN=postgres://… go test -p 1 -tags postgres ./pkg/database/... ./pkg/timezone/... ./migrations/
```
The tier fails when its variable is unset. `-p 1` because each package migrates into its own schema of one database, while `pg_trgm` is installed once per database: a second package running beside the first fails with `operator class gin_trgm_ops does not exist`. Under a plain `go test ./...` the suites that need a live dependency skip themselves instead — `TEST_DATABASE_URL` for the statement-timeout suite, a reachable Docker daemon for `pkg/docker` — and `go test` without `-v` does not print skips, so a green run can mean they never ran.
**Frontend.** Vitest for units; Playwright for the rest, in three tiers chosen by `E2E_TIER`:
-`mock` (default) — builds the production bundle, serves it, answers every call from a cassette;
-`local` — real backend from `docker-compose.e2e.yml` with a mock LLM (`e2e/tools/run-local-tier.sh`);
-`stand` — a deployed stand, needs `E2E_BASE_URL` and credentials.
Visual snapshots run only inside the pinned Playwright container (`pnpm run e2e:visual`); never on the host. The authoritative verdict of a run is `e2e/test-results/.last-run.json`, not the exit code of a piped command.
**The written playbooks live in `frontend/docs/`** and are worth reading before a manual pass: `e2e.md` (harness, cassettes, tiers, traps), `live-testing.md` (driving the real UI) and `list-detail-pages.md`.
## Writing Tests
Where a test lives and what it is called decide whether anyone finds it again. Each rule below is here because breaking it happened: `pkg/providers` grew 43 test files for 17 source files, one per fix, and seven of them each loaded the model catalogues to check a single property.
**Layout — one test file per source file.**
1. Tests of `x.go` live in `x_test.go`. A test for a bug, a feature or a regression goes into the test file of the source it pins — never into a new file named after the fix, the feature or the ticket. What decides the file is the code the test exists to pin, not the code it happens to execute most, and not the package it was written in: a test of `pconfig.GetOptionsForType` belongs in `pkg/providers/pconfig`.
2. The only other names: `fixtures_test.go` — test doubles shared by more than one test file of the package, and a package's catalogue of realistic sample inputs with their builders (the message chains of `pkg/cast`); `x_ext_test.go` — tests that must be `package <name>_test` because of an import cycle, with one line saying which; `x_live_test.go` — the `//go:build postgres` tier; `x_linux_test.go` and other GOOS/GOARCH suffixes — filename build constraints, never renamed away; `main_test.go` for `TestMain` and the tests of `main.go`; `example_test.go` for `Example…` functions only.
3. A helper defined in one test file and used by another is a hidden dependency: deleting the first breaks the second. Shared doubles live in `fixtures_test.go`, one per role — read it before writing another fake embedder, log recorder or Docker client.
**Names.**
4.`Test<Component>_<Unit>_<Behaviour>`: the source file in CamelCase, the one function or method under test, and what must hold — `TestTerminal_ExecCommand_KeepsPartialOutputOnTimeout`. Then `go test -run 'TestTerminal_'` selects a component and `-run 'TestTerminal_ExecCommand'` a unit. The name promises nothing the assertions do not check. Subtests are lower-case sentences.
**Before adding a test**, find the existing test of the same unit. The same setup with another input is a new row in its table, not a new function; the same input class with the same asserted outcome is a duplicate.
**Every assertion must be able to fail.** Each of these shipped here and stayed green with the behaviour it named removed:
5. A double standing in for a database, log or network write returns `ctx.Err()` once its context is done. One that ignores the context cannot tell a write on a cancelled context from a live one.
6. No expected value computed by the code under test or read from a production constant — a literal.
7. Test through the public entry — `Handle`, `Execute`, the Gin handler via `httptest`, `resolver.Mutation().X` — not the helper behind it, which stays green when the entry stops calling it.
8. Timing: lower bounds, or generous upper bounds as literals; a starved CI runner must not fail the test. Every blocking wait sits in a `select` with a timeout that fails with a reason. Parallel subtests do not share a double that mutates state.
9.`err != nil` does not say which error: use `errors.Is` or the distinguishing text.
**Proof and gates.**
10. A new or rewritten test is shown failing with its behaviour broken: mutate the production line its path takes, see `--- FAIL`, restore. Mutate in a throwaway copy of the tree — an interrupted script once left production code mutated in the working copy.
11. Run the package with `-race` — CI runs `go test ./... -race` — and without `-trimpath`, which breaks tests that open source files (`pkg/providers` parses `pkg/database/models.go`).
12. Renaming or moving a test file updates every document that names it, this one included, in the same change.
13. A test passes on any developer's machine, so it never depends on that machine's timezone, locale or installation. Build times in an explicit zone — `time.UTC`, or `Asia/Riyadh` (+03:00, no DST) where a non-zero offset matters — import `_ "time/tzdata"` wherever a zone is loaded by name, and never assert on what a local server happens to carry (its zone catalogue, its version). Prove a test that touches dates under `TZ=America/Los_Angeles`, `TZ=Asia/Shanghai` and `TZ=Pacific/Kiritimati`, and on the frontend also under `LC_ALL=zh_CN.UTF-8`; the Go test cache does not key on `TZ`, so run with `-count=1` or a zone-bound test comes back `(cached) ok`.
14. Coverage is not test strength: statement coverage of `pkg/csum` rose while 38% of its mutants still went unnoticed. A package that implements an algorithm over structured input — `pkg/cast` parsing, `pkg/csum` summarisation — is tested end to end on realistic inputs, step by step, with an exact assertion after every step, and its strength is measured by a mutation sweep, before and after any test is merged or deleted. Run that sweep one mutant at a time and cap each test binary's memory and time in its own process group: a mutated loop counter can allocate gigabytes in seconds, and killing `go test` leaves its test binary running.
## Architecture
@@ -69,82 +173,116 @@ The full stack runs at `https://localhost:8443` when using Docker Compose. Copy
| Package | Role |
|---|---|
| `cmd/pentagi/` | Main entry point; initializes config, DB, server |
| `cmd/pentagi/` | Entry point: config, tenant schema, DB pools, goose migrations, telemetry, Docker, providers, flow restore, HTTP server |
| `pkg/config/` | One env-tagged `Config`; validates `TENANT_ID` and derives the schema name. The widest dependency in the backend |
| `pkg/server/` | Gin engine and middleware. The work is in its subpackages: `services/` REST handlers, `models/` DTOs and their `Valid()` gates, `auth/` sessions + token JWTs + privilege checks, `oauth/`, `rdb/` filtering and paging, `response/`, `update/` |
| `pkg/controller/` | Flow/task/subtask agent runtime: spawns and stops workers, publishes agent, message, tool-call, terminal and screenshot logs to the subscription hub |
| `pkg/graph/` | gqlgen schema (`schema.graphqls`), resolvers, `model/` (generated) and `subscriptions/` (the pub/sub hub) |
| `pkg/database/` | sqlc-generated queries and models, tenant helpers, statement timeouts, and the legacy GORM handle. GORM *models* live in `pkg/server/models/` |
| `pkg/providers/` | LLM adapters. `provider/` holds the interface, the `ProviderType` constants and `AllProviderTypes`; `pconfig/` the per-agent model config; `openaicompat/` the shared OpenAI-shaped door; `embeddings/` a separate axis |
| `pkg/tools/` | The agent tool-call layer: schemas (`registry.go`), dispatcher (`executor.go`), and the tools — terminal, code, browser, memory, knowledge, `web_search` over `searchers/` |
| `pkg/docker/` | Docker SDK wrapper for the per-flow sandbox containers |
| `pkg/csum/` | Chain summarization for LLM context management, over the `chainAST` in `pkg/cast/` |
| `pkg/templates/` | Embedded agent prompts (`prompts/*.tmpl`) and the validator that checks a user-edited prompt still renders |
| `pkg/graphiti/` | HTTP client for the Graphiti knowledge-graph service. It does not speak Neo4j |
| `pkg/flowfiles/`, `pkg/resources/` | Per-flow file tree and sandbox transfer; the user-level resource store |
| `pkg/schema/`, `pkg/password/`, `pkg/system/`, `pkg/timezone/`, `pkg/version/`, `pkg/terminal/` | Validation plumbing; the password policy; shared HTTP client; IANA name resolution; link-time version; console output for the `cmd/*tester` CLIs |
Database migrations live in`backend/migrations/sql/` and run automatically via goose at startup.
Migrations are`backend/migrations/sql/*.sql`, **embedded into the binary** and run by goose at startup — a new migration needs a rebuild, not just a restart. A failure aborts the boot.
### Frontend Structure
```
frontend/src/
├── app.tsx / main.tsx # Entry points and router setup
State is managed primarily through Apollo Client (GraphQL) with real-time updates via GraphQL subscriptions over WebSocket.
Placement rule, as the code applies it: `components/ui` and `components/shared` never import `features/*` (ESLint rejects it); `components/ui` reaches the app only through the generic hooks in `hooks/`; `components/shared` holds composites that more than one area renders and takes its domain data through props (the version panel is the one that reads a domain provider); `features/<domain>` is where data coupling belongs — providers, generated types and REST calls — and a feature is normally consumed by its own domain's pages.
Server state comes from **Apollo Client 4** (note the v4 import paths, `@apollo/client/react`). `lib/apollo.ts` splits subscriptions onto a `graphql-ws` WebSocket link. Components seldom call Apollo directly: the queries and subscriptions live in `src/providers/*`, which `app.tsx` mounts around the router — add a new read there first. Not everything is GraphQL: account, resource and flow-file writes go over REST through `@/lib/axios`.
### Data Flow
1.User creates a "flow" (penetration test) via the UI or REST API.
2.The backend queues the flow and spawns agent goroutines.
3. The Researcher agent gathers information; the Developer plans attack strategies; the Executor runs tools in isolated Docker containers.
4.Results, tool outputs, and LLM reasoning are stored in PostgreSQL (with pgvector for semantic search/memory).
5. Real-time progress is pushed to the frontend via GraphQL subscriptions.
1.A user creates a "flow" — the UI calls the GraphQL `createFlow` mutation; REST is the programmatic equivalent.
2.`CreateFlow` (`pkg/controller/flows.go`) reserves the row and builds the worker asynchronously; there is no queue, and a build failure marks the flow `failed` and says so on its message log.
3. The `primary_agent` decomposes the flow into tasks; the `generator` produces each task's subtasks and the `refiner` re-plans after every completed one. Subtasks run one at a time and delegate to the specialist agents.
5. Results, tool output and LLM reasoning land in PostgreSQL (pgvector for semantic memory).
6. Progress reaches the UI through GraphQL subscriptions fed by `pkg/graph/subscriptions`.
7. Beside flows there is an **assistant**: an interactive chat attached to a flow, sharing its containers and provider settings but with its own log tables.
### Authentication
- **Session cookies** for browser login (secure, httpOnly)
- **OAuth2** via Google and GitHub
- **Bearer tokens** (API tokens table) for programmatic API access
- **Session cookies** for browser login — cookie store keyed by `COOKIE_SIGNING_SALT` mixed with `TENANT_ID`; `HttpOnly` always, `Secure` only over HTTPS. Changing the salt invalidates every session.
- **OAuth2** via Google and GitHub.
- **Bearer tokens** (API tokens table) for programmatic access.
All three pass through `pkg/server/auth/auth_middleware.go`, which offers `AuthUserRequired`, `AuthTokenRequired` and `TryAuth`. Authorization is separate: `auth.PrivilegesRequired("<area>.<action>")` wraps individual routes in `pkg/server/router.go`. Repeated failed logins are throttled.
### Key Integrations
- **LLM Providers**: OpenAI, Anthropic, Gemini, AWS Bedrock, Ollama, DeepSeek, GLM, Kimi, Qwen, and custom HTTP endpoints — configured via environment variables or the Settings UI
- **LLM Providers**: OpenAI, Anthropic, Gemini, AWS Bedrock, Ollama, DeepSeek, GLM, Kimi, Qwen, MiniMax, Mistral, xAI, and custom OpenAI-compatible endpoints. The authoritative list is `providerRegistry` in `backend/pkg/providers/registry.go` — check it before enumerating providers anywhere else.
- **Search**: DuckDuckGo, Google, Tavily, Firecrawl, Traversaal, Perplexity, Searxng, Sploitus and an internal browser-backed engine, all behind the single `web_search` tool. Authoritative list: `buildSearchEngines` in `backend/pkg/tools/web_search.go`.
- **Databases**: PostgreSQL + pgvector (required); Neo4j (optional) behind the Graphiti service, reached over HTTP.
1. Create `backend/pkg/providers/<name>/<name>.go` implementing the `provider.Provider` interface.
2. Add a new `Provider<Name> ProviderType` constant and `DefaultProviderName<Name>` in `pkg/providers/provider/provider.go`.
3. Register the provider in `pkg/providers/providers.go` (`DefaultProviderConfig`, `NewProvider`, `buildProviderFromConfig`, `GetProvider`).
4. Add the new type to the `Valid()` whitelist in `pkg/server/models/providers.go` — **without this step, the REST API returns 422 Unprocessable Entity**.
5. Add the env var key to `pkg/config/config.go` (e.g., `<NAME>_API_KEY`, `<NAME>_SERVER_URL`).
6. Add the new `PROVIDER_TYPE` enum value via a goose migration in `backend/migrations/sql/`.
7. Add the provider icon in `frontend/src/components/icons/<name>.tsx` and register it in `frontend/src/components/icons/provider-icon.tsx`.
8. Update the GraphQL schema/types and frontend settings page if needed.
The output of the generators below is committed — regenerate and commit in the same change. When a codegen input changes, `.github/workflows/ci.yml` regenerates `frontend/src/graphql/types.ts` and fails if the committed file differs; it does not check the gqlgen, sqlc or swag output, so a stale one compiles and merges unnoticed.
### Code Generation
| Change | Command (from) | Writes |
|---|---|---|
| `backend/pkg/graph/schema.graphqls` | `go run github.com/99designs/gqlgen --config ./gqlgen/gqlgen.yml` (`backend/`) | `pkg/graph/generated.go`, `pkg/graph/model/`, resolver stubs in `pkg/graph/schema.resolvers.go` |
| `backend/sqlc/models/*.sql`, a migration | `sqlc generate` (`backend/sqlc/`) — needs a **live** PostgreSQL in `DATABASE_URL` | `backend/pkg/database/` |
| `frontend/graphql-schema.graphql` (the operations file) or the backend schema | `pnpm run graphql:generate` (`frontend/`) | `frontend/src/graphql/types.ts` |
When modifying `backend/pkg/graph/schema.graphqls`, re-run the gqlgen command to regenerate resolver stubs. When modifying REST handler annotations, re-run swag to update Swagger docs. When modifying `frontend/src/graphql/*.graphql` query files, re-run `npm run graphql:generate` to update TypeScript types.
A backend schema change therefore needs **both** gqlgen and the frontend codegen.
### Utility Binaries
## Adding a New LLM Provider
The backend contains helper binaries for development/testing:
Order matters — types before the door, because the door's constructor names them. Copy the last provider added (`mistral`, `xai`) rather than an old one.
1.**Types.** In `pkg/providers/provider/provider.go`: the `Provider<Name>` and `DefaultProviderName<Name>` constants, the entry in `AllProviderTypes`, and the classification in `ReasoningProvider()`.
2.**Config.**`<NAME>_API_KEY` / `<NAME>_SERVER_URL` / `<NAME>_PROVIDER` in `pkg/config/config.go` (the third carries the gateway's model prefix), mirrored in `.env.example`, `docker-compose.yml` and the `clearConfigEnv` list in `config_test.go`. Add every credential field to `GetSecretPatterns()` — values listed there are masked out of logs and agent transcripts.
3.**Migration.** A goose migration that rebuilds the `PROVIDER_TYPE` enum with the new value and re-points `providers.type`, `flows.model_provider_type` and `assistants.model_provider_type`; Postgres will not extend that enum in place. Then regenerate `pkg/database/` with sqlc.
4.**Catalogue and door.**`pkg/providers/<name>/` with `config.yml`, `models.yml` and a `<name>.go` exporting `DefaultProviderConfig`, `BuildProviderConfig`, `DefaultModels` and `New`. An OpenAI-shaped vendor does not implement the interface by hand — `New` returns `openaicompat.New(openaicompat.Spec{…})`.
5.**Three tables, three edits**: `providerRegistry` (`registry.go`), `bundledCatalogs` (`catalog.go`), `doorEndpoints` (`routing.go`). Miss one and a guard test in `pkg/providers` fails.
6.**Installer.** The screen id, menu row, screen construction and strings under `cmd/installer/wizard/`. Nothing fails the build if you skip it; the wizard simply never offers the provider.
7.**GraphQL.** The `ProviderType` enum value plus fields in `ProvidersModelsList`, `ProvidersReadinessStatus` and `DefaultProvidersConfig`; re-run gqlgen and extend the per-type switches in `schema.resolvers.go`.
8.**Frontend.**`providerLabels` in `pages/settings/settings-providers.tsx` (a `Record<ProviderType, …>`, so it will not compile without the new key), the icon in `components/icons/` registered in `provider-icon.tsx`, the fields in `frontend/graphql-schema.graphql`, then `pnpm run graphql:generate`, and the e2e cassette in `e2e/mocks/cassettes/settings-providers.ts`.
9.**Docs.** The section every other provider has in `README.md`, `backend/docs/config.md` and `backend/docs/database.md`. `TestCatalog_ReadmeProviderSectionsMatchTheShippedConfig` in `pkg/providers/catalog_test.go` reads `README.md` — a provider or model missing from it turns that test red.
Embeddings are a separate axis (`EMBEDDING_PROVIDER`, `pkg/providers/embeddings/`): adding a chat door does not add an embedder.
## Adding a New Search Engine
Engines are primitives under `backend/pkg/tools/searchers/`, orchestrated by the single `web_search` tool. Agents never call an engine directly — they call `web_search` with an intent `mode`.
1.`searchers/<name>.go` implementing `searchers.Searcher`: constructor, `IsAvailable()`, `Engine()`, and a `Handle(ctx, Request)` returning **typed** errors (`searchers.Retryable` / `searchers.Fatal` / `searchers.ErrNotConfigured`, or `searchers.ClassifyHTTPStatus`). Never swallow an error into a result string. `searchers` must not import `pkg/tools`.
2. Config fields in `pkg/config/config.go`, plus `.env.example`, `docker-compose.yml`, the `envDefault` assertions in `config_test.go`, and `GetSecretPatterns()` for every credential.
3. Construct it in `buildSearchEngines` and place its id in the `fallbackStrategy` chains in `web_search.go` — the only place per-mode priority lives. An id in a chain with no entry in the engines map is skipped silently at runtime, not at compile time.
4. Attribution, if the engine needs a **new**`SearchengineType`: a goose migration rebuilding the enum, the constant in `pkg/database/models.go`, **and** the value in both the constant block and the `Valid()` switch in `pkg/server/models/searchlogs.go`. Reusing an existing value needs none of it.
5.`<name>_test.go` in `searchers/` (the shared MITM proxy harness is in `fixtures_test.go`), and orchestrator coverage in `web_search_test.go` if behaviour changes.
6. The installer wizard (`cmd/installer/wizard/`: the config field, the `GetVar`/`SetVar` pair, the descriptions and masked/critical lists, the labels, the form field) and `cmd/ftester` if you want to drive the engine in isolation.
7. The prose that enumerates engines: `pkg/templates/prompts/searcher.tmpl` (what the agent is told exists), `backend/docs/config.md`, and `README.md`.
No frontend change is needed: it treats `SearchLog.engine` as an opaque string.
## Utility Binaries
-`cmd/ctester/` — provider conformance tester: runs the case suite against one provider (`-type`), filtered by agent role and group, and writes a report. `-check-routing` checks catalogue routing only.
-`cmd/ftester/` — exercises LLM function/tool calling, including one search engine at a time.
-`cmd/etester/` — embedding tester and pgvector store maintenance. `flush` and `reindex` act on the real database in `DATABASE_URL` and are destructive.
-`cmd/installer/` — interactive TUI wizard for guided deployment (writes `.env`, compose files, DB and search settings). Its embedded files are generated: see `go generate` above.
PentAGI is **MIT licensed** and all dependencies use MIT-compatible licenses.
## For Developers
### Adding New Dependencies
When adding new dependencies, ensure they use compatible licenses:
#### Approved Licenses
- MIT
- Apache-2.0
- BSD-2-Clause, BSD-3-Clause
- ISC
- MPL-2.0 (if used without modification)
- 0BSD (public domain)
#### Incompatible Licenses
- GPL, LGPL, AGPL (without special exception)
- CC-BY-SA (for code, OK for data)
- Proprietary/Commercial licenses
### Before Merging PR
1. Update dependencies:
```bash
cd backend && go mod tidy
cd ../frontend && pnpm install
```
2. Generate license reports:
```bash
./scripts/generate-licenses.sh
```
This script automatically collects license information from all dependencies and saves them to the `licenses/` directory. See [licenses/README.md](licenses/README.md) for details.
This document recognizes all individuals who have contributed to PentAGI. Their work across 370+ commits over 18 months has shaped this project into what it is today.
- Agent chain iteration cap and repeating detector ([PR#178](https://github.com/vxcontrol/pentagi/pull/178), [PR#180](https://github.com/vxcontrol/pentagi/pull/180))
- HTTP client global mutation in search tools ([PR#151](https://github.com/vxcontrol/pentagi/pull/151))
This project exists because of the collective effort of everyone listed above. From major feature implementations to small bug fixes, every contribution has made PentAGI better.
---
## How to Contribute
Interested in contributing to PentAGI? We welcome contributions of all kinds:
- Bug reports and fixes
- New features and enhancements
- Documentation improvements
- Testing and QA
- Code reviews
Please see our [CONTRIBUTING.md](CONTRIBUTING.md) guide for more information.
---
**Note:** Due to repository history rewriting on March 29, 2026, to resolve licensing matters, individual commit history is no longer visible in GitHub's interface. This document preserves the record of all contributions made during the project's development from January 2025 to March 2026.
resultObj=fmt.Sprintf("Mock content of file: %s\nThis is a sample content that would be read from the file.\nIt contains multiple lines to simulate a real file.",fileArgs.Path)
builder.WriteString(fmt.Sprintf("## Snippet\n\nThis is a detailed mock snippet for search result %d that matches your query '%s'. It contains relevant information that would be returned by the real Google search API.\n\n",i,searchArgs.Query))
fmt.Fprintf(&builder,"# %d. Mock Google Result %d for '%s'\n\n",i,i,searchArgs.Query)
fmt.Fprintf(&builder,"## Snippet\n\nThis is a detailed mock snippet for search result %d that matches your query '%s'. It contains relevant information that would be returned by the real Google search API.\n\n",i,searchArgs.Query)
builder.WriteString(fmt.Sprintf("## Description\n\nThis is a detailed mock description for search result %d that matches your query '%s'. DuckDuckGo would provide this kind of anonymous search result.\n\n",i,searchArgs.Query))
fmt.Fprintf(&builder,"# %d. Mock DuckDuckGo Result %d for '%s'\n\n",i,i,searchArgs.Query)
fmt.Fprintf(&builder,"## Description\n\nThis is a detailed mock description for search result %d that matches your query '%s'. DuckDuckGo would provide this kind of anonymous search result.\n\n",i,searchArgs.Query)
builder.WriteString(fmt.Sprintf("This is a comprehensive answer to your query '%s' that would be generated by Tavily AI. It synthesizes information from multiple sources to provide you with the most relevant information.\n\n",searchArgs.Query))
fmt.Fprintf(&builder,"This is a comprehensive answer to your query '%s' that would be generated by Tavily AI. It synthesizes information from multiple sources to provide you with the most relevant information.\n\n",searchArgs.Query)
builder.WriteString(fmt.Sprintf("* Match score %.3f\n\n",0.95-float64(i-1)*0.1))
builder.WriteString(fmt.Sprintf("### Short content\n\nHere is a brief summary of the content from this search result related to '%s'.\n\n",searchArgs.Query))
builder.WriteString(fmt.Sprintf("### Content\n\nThis is the full detailed content that would be retrieved from the URL. It contains comprehensive information about '%s' that helps answer your query with specific facts and data points that would be relevant to your search.\n\n",searchArgs.Query))
fmt.Fprintf(&builder,"## %d. Mock Tavily Result %d\n\n",i,i)
fmt.Fprintf(&builder,"* Match score %.3f\n\n",0.95-float64(i-1)*0.1)
fmt.Fprintf(&builder,"### Short content\n\nHere is a brief summary of the content from this search result related to '%s'.\n\n",searchArgs.Query)
fmt.Fprintf(&builder,"### Content\n\nThis is the full detailed content that would be retrieved from the URL. It contains comprehensive information about '%s' that helps answer your query with specific facts and data points that would be relevant to your search.\n\n",searchArgs.Query)
fmt.Fprintf(&builder,"# Mock web_search result (mode=%s)\n\n",mode)
fmt.Fprintf(&builder,"The web_search orchestrator would pick the best available engine for mode '%s', retry transient failures, and fall back across providers automatically.\n\n",mode)
switchmode{
case"links":
builder.WriteString("# Links\n\n")
fori:=1;i<=n;i++{
fmt.Fprintf(&builder,"## %d. Mock result %d\n\n* URL https://example.com/web_search/result%d\n\n### Snippet\n\nBrief snippet about '%s'.\n\n",i,i,i,searchArgs.Query)
fmt.Fprintf(&builder,"# Answer\n\nThis is a synthesized mock answer to '%s' that web_search would return in mode '%s', combining multiple sources.\n",searchArgs.Query,mode)
fmt.Fprintf(&builder,"### Short content\n\nHere is a brief description of the content from this search result related to '%s'.\n\n",searchArgs.Query)
fmt.Fprintf(&builder,"### Raw content for %d. Mock Firecrawl Result %d\n\nThis is the full scraped markdown content that Firecrawl would retrieve from the URL. It contains comprehensive information about '%s' that helps answer your query with specific facts and data points relevant to your search.\n\n",i,i,searchArgs.Query)
builder.WriteString(fmt.Sprintf("Here is the Traversaal answer to your query '%s'. Traversaal provides concise answers based on web information with relevant links for further exploration.\n\n",searchArgs.Query))
fmt.Fprintf(&builder,"Here is the Traversaal answer to your query '%s'. Traversaal provides concise answers based on web information with relevant links for further exploration.\n\n",searchArgs.Query)
builder.WriteString(fmt.Sprintf("This is a detailed research report from Perplexity AI about '%s'. Perplexity provides comprehensive answers by synthesizing information from various sources and augmenting it with AI analysis.\n\n",searchArgs.Query))
fmt.Fprintf(&builder,"This is a detailed research report from Perplexity AI about '%s'. Perplexity provides comprehensive answers by synthesizing information from various sources and augmenting it with AI analysis.\n\n",searchArgs.Query)
builder.WriteString("The query you've asked about requires examining multiple perspectives and sources. Based on recent information, here's a thorough analysis of the topic with key insights and developments.\n\n")
builder.WriteString("First, it's important to understand the background of this subject. Several authoritative sources indicate that this is an evolving area with recent developments. The most current research suggests that...\n\n")
builder.WriteString(fmt.Sprintf("This is a mock response from the Searxng meta search engine for query '%s'. In a real implementation, this would return actual search results aggregated from multiple search engines with customizable categories, language settings, and safety filters.\n\n",searchArgs.Query))
fmt.Fprintf(&builder,"This is a mock response from the Searxng meta search engine for query '%s'. In a real implementation, this would return actual search results aggregated from multiple search engines with customizable categories, language settings, and safety filters.\n\n",searchArgs.Query)
builder.WriteString(fmt.Sprintf(" Content: This is a mock content snippet that would appear in a real Searxng search result. It contains relevant information about '%s' that helps answer your query.\n\n",searchArgs.Query))
fmt.Fprintf(&builder,"%d. **Mock Result %d** - Mock title about %s\n",i,i,searchArgs.Query)
fmt.Fprintf(&builder," Content: This is a mock content snippet that would appear in a real Searxng search result. It contains relevant information about '%s' that helps answer your query.\n\n",searchArgs.Query)
builder.WriteString(fmt.Sprintf("# Task ID %d\n\n",searchMemoryArgs.TaskID.Int64()))
fmt.Fprintf(&builder,"# Task ID %d\n\n",searchMemoryArgs.TaskID.Int64())
}
ifsearchMemoryArgs.SubtaskID!=nil{
builder.WriteString(fmt.Sprintf("# Subtask ID %d\n\n",searchMemoryArgs.SubtaskID.Int64()))
fmt.Fprintf(&builder,"# Subtask ID %d\n\n",searchMemoryArgs.SubtaskID.Int64())
}
builder.WriteString("# Tool Name 'terminal'\n\n")
builder.WriteString("# Tool Description\n\nCalls a terminal command in blocking mode with hard limit timeout 1200 seconds and optimum timeout 60 seconds\n\n")
builder.WriteString("# Tool Description\n\nCalls a terminal command in blocking mode. Use timeout=0 or a negative value to apply the configured server default timeout. Explicit positive values are accepted up to 10800 seconds (3 hours); values outside this range are replaced by the server default\n\n")
builder.WriteString("# Chunk\n\n")
builder.WriteString(fmt.Sprintf("This is a memory chunk related to your questions '%s'. It contains information about previous commands, outputs, and relevant context that was stored in the vector database.\n\n",questionsText))
fmt.Fprintf(&builder,"This is a memory chunk related to your questions '%s'. It contains information about previous commands, outputs, and relevant context that was stored in the vector database.\n\n",questionsText)
resultObj=fmt.Sprintf("# Original Guide Type: pentest\n\n# Original Guide Questions\n\n%s\n\n## Penetration Testing Guide\n\nThis guide provides a step-by-step approach for conducting a penetration test on the target system.\n\n### 1. Reconnaissance\n- Gather information about the target using OSINT tools\n- Identify potential entry points and attack surfaces\n\n### 2. Scanning\n- Use tools like Nmap to scan for open ports and services\n- Identify vulnerabilities using automated scanners\n\n### 3. Exploitation\n- Attempt to exploit identified vulnerabilities\n- Document successful attack vectors\n\n### 4. Post-Exploitation\n- Maintain access and explore the system\n- Identify sensitive data and potential lateral movement paths\n\n### 5. Reporting\n- Document all findings with proof of concept\n- Provide remediation recommendations\n\n",questionsText)
}elseifsearchGuideArgs.Type=="install"{
case"install":
resultObj=fmt.Sprintf("# Original Guide Type: install\n\n# Original Guide Questions\n\n%s\n\n## Installation Guide\n\n### Prerequisites\n- Operating System: Linux/macOS/Windows\n- Required dependencies: [list]\n\n### Installation Steps\n1. Download the software from the official repository\n ```bash\n git clone https://github.com/example/software.git\n ```\n\n2. Navigate to the project directory\n ```bash\n cd software\n ```\n\n3. Install dependencies\n ```bash\n npm install\n ```\n\n4. Build the project\n ```bash\n npm run build\n ```\n\n5. Verify installation\n ```bash\n npm test\n ```\n\n### Troubleshooting\n- Common issue 1: [solution]\n- Common issue 2: [solution]\n\n",questionsText)
}else{
default:
resultObj=fmt.Sprintf("# Original Guide Type: %s\n\n# Original Guide Questions\n\n%s\n\n## Guide Content\n\nThis is a comprehensive guide for the requested type '%s'. It contains detailed instructions, best practices, and examples tailored to your specific questions.\n\n### Section 1: Getting Started\n[Detailed content would be here]\n\n### Section 2: Main Procedures\n[Step-by-step instructions would be here]\n\n### Section 3: Advanced Techniques\n[Advanced content would be here]\n\n### Section 4: Troubleshooting\n[Common issues and solutions would be here]\n\n",searchGuideArgs.Type,questionsText,searchGuideArgs.Type)
mockCode="def example_function(param1, param2='default'):\n \"\"\"This is an example Python function that demonstrates a pattern.\n \n Args:\n param1: The first parameter\n param2: The second parameter with default value\n \n Returns:\n The processed result\n \"\"\"\n result = {}\n \n # Process the parameters\n if param1 is not None:\n result['param1'] = param1\n \n # Additional processing\n if param2 != 'default':\n result['param2'] = param2\n \n return result\n\n# Example usage\nif __name__ == '__main__':\n output = example_function('test', 'custom')\n print(output)"
mockCode="/**\n * Example JavaScript function that demonstrates a pattern\n * @param {Object} options - Configuration options\n * @param {string} options.name - The name parameter\n * @param {number} [options.count=1] - Optional count parameter\n * @returns {Object} The processed result\n */\nfunction exampleFunction(options) {\n const { name, count = 1 } = options;\n \n // Input validation\n if (!name) {\n throw new Error('Name is required');\n }\n \n // Process the data\n const result = {\n processedName: name.toUpperCase(),\n repeatedCount: Array(count).fill(name).join(', ')\n };\n \n return result;\n}\n\n// Example usage\nconst output = exampleFunction({ name: 'test', count: 3 });\nconsole.log(output);"
}else{
mockCode=fmt.Sprintf("// Example code in %s language\n// This is a mock code snippet that would be returned from the vector database\n\n// Main function definition\nfunction exampleFunction(param) {\n // Initialization\n const result = [];\n \n // Processing logic\n for (let i = 0; i < param.length; i++) {\n result.push(processItem(param[i]));\n }\n \n return result;\n}\n\n// Helper function\nfunction processItem(item) {\n return item.transform();\n}",searchCodeArgs.Lang)
default:
mockCode=fmt.Sprintf("// Example code in %s language\n// This is a mock code snippet that would be returned from the vector database\n\n// Main function definition\nfunction exampleFunction(param) {\n // Initialization\n const result = [];\n \n // Processing logic\n for (let i = 0; i < param.length; i++) {\n result.push(processItem(param[i]));\n }\n \n return result;\n}\n\n// Helper function\nfunction processItem(item) {\n return item.transform();\n}",searchCodeArgs.Lang.String())
}
resultObj=fmt.Sprintf("# Original Code Questions\n\n%s\n\n# Original Code Description\n\nThis code sample demonstrates the implementation pattern for handling the specific scenarios you asked about. It includes proper error handling, input validation, and follows best practices for %s.\n\n```%s\n%s\n```\n\n",questionsText,searchCodeArgs.Lang,searchCodeArgs.Lang,mockCode)
{name:"a configured proxy wins and keeps its credentials",proxy:"http://user:secret@proxy.internal:3128",wantHost:"proxy.internal:3128",wantUser:"user"},
{name:"without one the environment proxy is honoured",proxy:"",wantHost:"env-proxy.internal:8080"},
{name:"an unparsable proxy is refused",proxy:"://nope",wantErr:"not a valid URL"},
{name:"a proxy without a host is refused",proxy:"not a url at all",wantErr:"has no host"},
{name:"a zero config talks to the default server anonymously",cfg:Config{},wantVersion:"0.0.0"},
{name:"a development build is sent as the unknown version",cfg:Config{InstallerVersion:"develop-87ac00f"},wantVersion:"0.0.0"},
{name:"an unusable license key is reported, not fatal",cfg:Config{LicenseKey:"NOT-A-REAL-LICENSE"},wantWarning:"license key is not usable",wantVersion:"0.0.0"},
{name:"a plaintext update server is refused",cfg:Config{Host:"http://update.pentagi.com"},wantErr:"always encrypted"},
{name:"an unusable proxy is refused",cfg:Config{ProxyURL:"://nope"},wantErr:"not a valid URL"},
t.Error("List() with 'observability' prefix did not include any observability files")
tests:=[]struct{
namestring
embeddedbool
filestring
setupfunc(t*testing.T,fFiles,workstring)
wantFileStatus
}{
{name:"a file absent from the working directory is missing",file:"test.txt",want:FileStatusMissing},
{name:"an exact copy of a linked file is ok",file:"test.txt",setup:copyOf("test.txt"),want:FileStatusOK},
{name:"a linked file with other content is modified",file:"test.txt",setup:write("test.txt","modified content"),want:FileStatusModified},
{name:"a linked file with other permissions is modified",file:"run.sh",setup:copyWithMode("run.sh",0o644),want:permMismatch},
{name:"an exact copy of an embedded file is ok",embedded:true,file:"docker-compose.yml",setup:copyOf("docker-compose.yml"),want:FileStatusOK},
{name:"an embedded file with other permissions is modified",embedded:true,file:"docker-compose.yml",setup:copyWithMode("docker-compose.yml",0o755),want:permMismatch},
{
name:"an embedded file with other bytes of the same size is modified",
{name:"an embedded file of another size is modified",embedded:true,file:"docker-compose.yml",setup:write("docker-compose.yml","different size content"),want:FileStatusModified},
}
// test listing with non-existent prefix
emptyFiles,err:=f.List("nonexistent-prefix")
iferr!=nil{
t.Fatalf("List() with non-existent prefix error = %v",err)
}
iflen(emptyFiles)!=0{
t.Errorf("List() with non-existent prefix returned %d files, want 0",len(emptyFiles))
for_,tt:=rangetests{
t.Run(tt.name,func(t*testing.T){
f:=filesLinksFixture(t)
iftt.embedded{
filesRequireEmbedded(t)
// As a released installer runs: no links directory to take an expected mode from.
require.Len(t,started,1,"started announced %d times",len(started))
require.Len(t,completed,1,"the screen was told the operation finished %d times",len(completed))
assert.Equal(t,tc.stack,started[0].Stack)
assert.Equal(t,tc.stack,completed[0].Stack,"the completion must name the stack asked about, not a nested one")
iftc.wantErr==""{
require.NoError(t,err)
assert.NoError(t,completed[0].Error)
return
}
require.EqualError(t,err,tc.wantErr)
assert.EqualError(t,completed[0].Error,tc.wantErr,"the one completion the screen sees must carry the failure")
})
}
}
Loaded 100 of 1379 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.