Uipath rpa
Always invoke for `.xaml`/`.cs` workflow files. UiPath RPA (Modern or Legacy): create, edit, validate, build, pack, run, debug coded `.cs` and `.xaml` workflows; UI automation with Object Repository selectors; live desktop/browser UI exploration/control; test case authoring; Integration Service connector calls. Packing stays here; solution-level `.uipx` deployment→uipath-solution; non-solution Orchestrator ops→uipath-platform; test reports→uipath-test; agents→uipath-agents.
By- name:
- uipath-rpa
- description:
- Always invoke for `.xaml`/`.cs` workflow files. UiPath RPA (Modern or Legacy): create, edit, validate, build, pack, run, debug coded `.cs` and `.xaml` workflows; UI automation with Object Repository selectors; live desktop/browser UI exploration/control; test case authoring; Integration Service connector calls. Packing stays here; solution-level `.uipx` deployment→uipath-solution; non-solution Orchestrator ops→uipath-platform; test reports→uipath-test; agents→uipath-agents.
UiPath RPA Assistant
Create, edit, manage, validate, build, run, debug, test, and publish UiPath coded (C#) and XAML automations. One UIA activity set covers Windows/macOS, desktop/web, strict/fuzzy selectors with anchors, Computer Vision, and semantic matching; uia-configure-target selects and automatically falls back between routes.
<!--skill-flavor:host-scope:start--> <!--skill-flavor:host-scope:end-->Read referenced files imperatively. This SKILL.md routes you; it does not replace references. When a rule, Task Navigation entry, or section points to a file, open and read it in full before acting—do not grep, skim, use
--help, or substitute prior knowledge. Catalogs may prescribe targeted lookup (for example, Grep^##for contents or<command> --helpfor flags); read matching sections only. A pointer naming a section (file.md § Section) is targeted through the next heading of its level. Skipped or partial references commonly cause build/runtime errors.
When to Use This Skill
Use for projects, workflows, tests, source files, configuration, dependencies, activities, validation/build/run/debug, assertions, Integration Service connectors, and desktop/web UI automation.
UIA Prerequisites
UIA work requires UiPath.UIAutomation.Activities at or above the minimum version in uia-starter-guide.md § UIA Prerequisites; never hardcode it. Install or upgrade it through § Resolving Packages & Activity Docs, Step 1.
Precondition: Project Context
<!--skill-flavor:project-context-precondition:start-->Before work, check .claude/rules/project-context.md in the project directory. If present and fresh, proceed. If missing/stale, run the skip gate and, only if it does not trip, perform environment-setup.md § Project Context Discovery: metadata-comment counts versus current counts, the 60–70% threshold, greenfield/empty/untouched-scaffold skip gate, host-specific discovery-agent options, and context-files:/SKIP: handling. The agent writes context files; do not re-read or rewrite them. Dispatch discovery AT MOST ONCE per session — reuse a running agent or its produced result; a later step that calls for project-context discovery means INTEGRATE the earlier dispatch, never spawn a second. If the skip gate trips, use no discovery agent and write both context files yourself after build per that section.
Step 0: Resolve PROJECT_DIR
Before creating/modifying anything, resolve the project using environment-setup.md § Step 0.1. Find project.json to establish {projectRoot}; no Studio Desktop check is needed for the standard loop. uip rpa auto-launches a headless Studio (UiPath.Studio.Helm NuGet) on first call. Studio Desktop is required only for files diff and focus-activity. Coded UI ObjectRepository.cs (Descriptors.*) regenerates on per-file validate after a [Workflow]/[TestCase] .cs exists (§ Capture-First Fast Path step 2; coded/operations-guide.md § Configure UI Targets).
A ~<name> file beside a workflow (~Main.xaml, ~Process.cs) is Studio Desktop's backup of unsaved designer changes, not a workflow: exclude it from file listings and never edit, validate, delete, or commit it. Before editing <name> itself, follow environment-setup.md § Rules, Rule 5.
Project Type Detection
After resolving PROJECT_DIR, inspect project.json targetFramework first:
"Legacy"or absent in an older project: Legacy mode. Stop and follow references/legacy/legacy-mode-guide.md. Use standaloneuip rpa-legacy, .NET Framework 4.6.1, classic activities without “X”, andmscorlib; modern rules do not apply."Windows"or"Portable": Modern mode; useuip rpa.Windowsmeans modern Windows-only, not Windows-Legacy.
Use uip rpa-legacy only for Legacy, never because uip rpa is unavailable; it can pack Modern projects with exit 0, so fix uip rpa instead.
Modern mode: coded = .cs with [Workflow]/[TestCase] and no workflow .xaml beyond scaffolded Main.xaml; XAML = workflow .xaml and no coded workflow .cs; both = hybrid, consult coded-vs-xaml-guide.md and match the request; neither = new project, default XAML. Switch to coded only for explicit “coded”, “.cs”, “C# workflow”, “coded test case”, or coded-specific triggers (DTOs/custom models/unit-testable business logic). Otherwise “create a workflow”, “automate X”, and “build an automation” mean XAML. Route through Task Navigation; Legacy follows its guide.
Authoring Mode Selection
Match existing mode; new or ambiguous work defaults to XAML. Switch to coded only on explicit user phrasing or a coded-specific trigger from the table below.
| Scenario | Mode | Why |
|---|---|---|
| Standard RPA (Excel, email, file ops) | XAML (default) | Direct activity support, no code needed |
| UI automation | XAML (default) | Full activity support; coded also works via uiAutomation service |
| Integration Service connectors (XAML) | XAML | IS connector activities use XAML-specific dynamic activity config |
| No matching activity for a subtask | Coded fallback | Small .cs invoked from XAML via Invoke Workflow File |
| Complex data transforms, HTTP, parsing | Coded | C# is more natural than nested XAML activities |
| Tempted to call a PowerShell script | Coded | Prefer a coded workflow. If PS is genuinely needed (admin cmdlets, existing .ps1), use the InvokePowerShell<T> activity — never Invoke Process + powershell.exe. See powershell-interop-guide.md |
| Custom data models / DTOs | Coded Source File | XAML cannot define types — plain .cs, no CodedWorkflow base |
| Unit tests with assertions | Coded Test Case | [TestCase] with Arrange/Act/Assert |
| Project edited in Studio Web, a process a Flow solution starts included | XAML, VB expressions | Studio Web opens no project holding coded workflows or C# expressions (Common Rule 2a) |
| User explicitly requests coded/XAML | User's choice | Never second-guess explicit preference |
UI Automation Boundaries
For opening apps/browsers, clicking, typing, scraping visible UI, submitting forms, or verifying UI state, use UiPath UIA only: XAML NApplicationCard plus UIA activities; coded uiAutomation.Open/Attach plus Object Repository descriptors; or, where the package's coded authoring guide § Selector-Only Targets allows it, CLI-captured selectors via TargetAppModel / Target.FromSelector (coded). Do not substitute InvokeCode, PowerShell, Selenium, Playwright, CDP, raw DOM JavaScript, HTTP form posts, or external browser drivers. Coded fallback is only for non-UI helpers. If target configuration is unavailable, use the documented UIA indication path, never an external shortcut.
Read {PROJECT_DIR}/.local/docs/packages/UiPath.UIAutomation.Activities/ui-automation-guide.md § Mandatory: Generate Targets Before Writing Any UI Code — read it in full per Rule 7 before any UIA work; it owns the prohibited-tool list, UIA-only exploration, and InvokeJS/InjectJsScript exception scope.
Placeholder-Selector Stub Pattern (when live app access is unavailable)
Without live app access, emit real UIA activities with placeholder selector strings and TODO Indicate markers, never Log stubs: use real NTypeInto, NClick, NGetText, NApplicationCard, etc.; put TODO Indicate in XAML DisplayName or adjacent coded // TODO[Indicate]. Applies to XAML and coded; read uia-policies-catalog.md § Placeholder-Selector Stub Pattern. It needs no UIA package or CLI. Do not create workflows whose UI steps merely log intentions. Hybrid orchestration is Main.xaml → InvokeWorkflowFile → coded helper; see coded-vs-xaml-guide.md for the full flowchart, InvokeCode extraction rules, and patterns.
Capture-First Fast Path
For dialog/form automation or UI tests from manual steps, defer authoring prerequisites until capture:
- Per Rule 7, read uia-starter-guide.md, the UIA package core guide, and its mandated target-capture orchestration reference, all in full.
- Coded only: install every needed activity package and write an empty
[Workflow] public void Execute() { }class (namespace per Rule 17) before the firstuip rpacall, including window baseline. The first host load snapshots.local/.codedworkflows/; without packages/stub authoring can hitCS0246 'CodedWorkflow'.uip rpa project close --project-dir "<PROJECT_DIR>"clears it. Latervalidaterefreshes onlyObjectRepository.cs;CodedWorkflow.csservice accessors andworkflows.Xcross-calls remain first-load snapshots, so a later package install or new cross-called workflow needs a regen; see coded/operations-guide.md § Configure UI Targets. - Run the package guide’s Window Baseline: list top-level windows once and decide whether to launch.
- Inventory manual steps from Test Manager, PDD, or script. Map each “Click/Enter/Select/Verify” to one OR element, group by screen (package guide § Capturing from Manual Test Steps), and decide every element and screen name now — apply them verbatim during capture.
- Capture screen by screen with
uia-configure-targetand screen advancement (package guide § Multi-Step UI Flows); author only at screen boundaries, never between calls within a screen. - Integrate already-dispatched context discovery (at-most-once, never a second spawn), read the mode authoring guide in full, author, and validate. Coded: validate once to regenerate
ObjectRepository.cs, read it, and reference every target asDescriptors.<App>.<Screen>.<Element>; use member names from that file, never capture OR names, and never author against string target names while it is absent.
Skip this path when the task has no UI surface (data transforms, IS connector calls, headless file/email automation). Also skip it when the task HAS a UI surface but no live app to capture against (app not installed, no GUI, capture deferred to a developer) — use the § Placeholder-Selector Stub Pattern instead, or, in a migration, the source's recorded targets (Rule 7). Window Baseline does not prove an app/GUI exists; verify separately or ask.
Session Pre-warm
When more than one heavy uip rpa call is expected, background at session start:
uip rpa activities find --query log --output json > /dev/null 2>&1 &
The first heavy call costs about 22s, shared by validate/build/run/activities get-default-xaml/analyzer-rules list; skip for zero/one heavy call. In Windows PowerShell use Start-Process powershell.exe -ArgumentList ... (not pwsh) because & does not background; never Start-Process -FilePath "uip" or any .ps1 (Notepad opens it).
Critical Rules
Common Rules are 1–12. Coded rules 13–19 are in coded/codedworkflow-reference.md § Critical Rules — Coded. XAML rules are independent 16–24/25a: 16–21a and 24–25a in xaml/xaml-basics-and-rules.md § Critical Rules — XAML, with 22–23 below. [Coded]/[XAML] disambiguates repeated numbers; Cross-references (“Common Rule 10”, “Rule 21”, “Rule 24”) always point to a uniquely-numbered rule.
Common Rules (Both Modes)
- NEVER create a project without confirming none exists. Check explicit path, project name, then CWD for
project.json; create only when no match exists and the user explicitly requests creation.<!--skill-flavor:rules-project-creation:start--> - ALWAYS use
uip rpa init; never manually writeproject.jsonor scaffolding. Before init, if the user names a template ("REFramework", "based on the X template") or an industry/domain pattern (SAP, ERP, banking, mainframe), runuip rpa templates search --query "<term>" --output jsonand follow environment-setup.md § Template selection: never silently choose Marketplace; present candidates and ask; if Official and Marketplace both match, ask. 2a. Pass--target-frameworkAND--expression-languageexplicitly on everyuip rpa init— never omit them. Both are immutable after creation (Rule 23); omitting--target-frameworksilently yields a Windows project. ChoosePortablefor cross-platform/non-Windows runtime (Linux, container, serverless) or Studio Web; chooseWindowsfor Windows runtime using Windows-only capabilities (Excel COM, classic Office, WPF /PresentationFramework, Windows-only UIA) or Studio Desktop (Windowsis not editable in Studio Web). Studio Web accepts Portable only when every workflow is XAML with VB expressions; errors are20042 Project has coded workflowsand20021 ... unsupported programming language: CSharp, and the project then opens only in Studio Desktop. A request requiring both cross-platform runtime and Windows-only capability is contradictory—surface it. Windows - Legacy is a last resort (explicit ask or hard .NET 4.6.1 need; never inferred from VB.NET or non-"X" classic activities) — create it in Legacy mode, not moderninit. No signal →AskUserQuestionabout Windows versus Cross-platform, framed around runtime host.--expression-languagedefaults toVisualBasic; useCSharponly explicitly.initwrites installed StudiodotNetVersion; unsupported robot versions fault before activities withError converting value "<VERSION>" to type 'UiPath.Shared.DotNetVersion'; then setdotNetVersionto the robot version (net8.0wherenet10.0is refused), rebuild, and republish.<!--skill-flavor:rules-project-creation:end--> <!--skill-flavor:rules-validation-gate:start--> - Phase-gated validation. After every create/edit, run
uip rpa validate --file-path "<FILE>" --project-dir "<PROJECT_DIR>" --output jsonuntil 0 errors, fixing one thing per iteration; after every touched file is clean, runuip rpa build "<PROJECT_DIR>" --output jsonuntil clean.validatecatches structural XAML, references, and schema;buildcovers all project workflows, analyzer rules, and packaging. The split is cli-reference.md § What each phase covers. Ifbuilderrors, take each error's file from the build's detailed log and re-runvalidate --file-pathon it for a compile error. Limit each file validation loop and separate build loop to 5 attempts. A smoke test does not replace build; preferrun --skip-buildafter a passing build (cli-reference.md § Smoke Test). Do not runuip rpa analyzer-rules listas an authoring prerequisite; use it only on request or after repeated rule-family violations (the unscoped call can take a minute or more; cli-reference.md § analyzer-rules list). Warnings do not gate delivery, naming warnings excepted (Rule 4c): with 0 errors from validate/build, deliver; investigate warnings only on request or acceptance impact. Report warning counts by rule ID; do not spend gate attempts on them. Expected UIA warnings (verification-feature, Automation Hub URL) are at cli-reference.md § Expected non-defect warnings. Read errors in full. See cli-reference.md § Validation Iteration Loop. - Always validate every touched file and verify project build before declaring done. Clean validate alone is insufficient; for observable-output workflows, finish with one
runand check outputs (execution-maps-guide.md § Gate ≠ runtime proof).<!--skill-flavor:rules-validation-gate:end--> 4a. Use file tools:Writeeach.xaml/.cscompletely andEditlater; never generate workflow files with scripts/templates: validation and fixes stay per file, and Object Repository links surviveEditbut not regeneration. For similar files, parallelWrites, a helper workflow, or copy a validated file andEditdifferences. 4b. Write only invokable units: extract reused or independently readable groups; keep one activity or short assignments inline. Do not wrap one activity merely to pass arguments. A scope the activity needs (an Application Card, an attach) is no reason to extract it: open the scope at the step, around the steps that act on that window in a row. 4c. Name XAML workflow arguments and variables by the Workflow Analyzer naming rules in force — entry points and library public workflows included — and clear every naming warningbuildreports (validatedoes not run the analyzer). Default rules: direction prefix on arguments (in_InvoiceId,out_Result,io_Browser; ST-NMG-002);dt_after it on a DataTable argument (in_dt_Rows; ST-NMG-011) and first on a DataTable variable (dt_Rows; ST-NMG-009); then letters, digits only at the end (in_dt_InvoiceRows, notin_dt_Invoice_Rows). An organization can change the rules; a warning's pattern overrides these defaults. No prefix: coded workflow arguments (coded/operations-guide.md § Add a Workflow File to Existing Project, step 3), the Global Exception Handler'serrorInfoandresult(error-handling-guide.md § Global Exception Handler), test-data arguments (testing-guide.md § Data-Driven Testing). Library public arguments: library-authoring-guide.md § The Public-Workflow Contract. - Prefer UiPath built-in activities for Orchestrator integration, UIA, and documents; use plain .NET/third-party packages for pure transforms, HTTP, and parsing, but reach a third-party system through an Integration Service connector, or build one with
uip is connectors builder; a direct API call needs a stated reason. 5a. A secret stays in its asset until the scope that uses it. Read a Credential or Secret asset (Get Credential, Get Secret, or their coded equivalents) inside the scope that types or sends the secret — the application card of the sign-in, the request that carries it — and pass only the asset's name between workflows and through the configuration. A password passed as an argument,SecureStringorString, or kept in a dictionary reaches every workflow it crosses; the analyzer refuses only theSecureStringworkflow argument (ST-SEC-007, cli-reference.md § Analyzer errors). Where a connection holds the secret (an Integration Service connection), use the connection. - ALWAYS ensure required package dependencies are in
project.jsonbefore using their activities or services. 6a. Before serialization, remove only dependencies listed unused byuip rpa cleanup --dry-run(cli-reference.md § packages install); packages may be sole suppliers, e.g.MergePDFsin IntelligentOCR.StudioWeb. Before writing an activity tag, runuip rpa activities find --query "<verb>" --output json, use returnedClassName, and never derive tags from display names (common-pitfalls.md § Common Activity Name Confusions). - [UIA] Before any UIA activity (
<uix:N*>,uiAutomation.*, orDescriptors.*), MUST read references/uia-starter-guide.md in full; the skill's conditional UIA policies are entries of references/uia-policies-catalog.md, each read when its condition holds. Then read the package core guide in full and, before authoring, the mode authoring guide in full as routed by its § Documentation. No exceptions for "simple" UIs. Never hand-write selectors; useuia-configure-targetexclusively; selector-only coded work skips only OR registration, not capture. A migration is the exception: it registers the targets its source recorded, as translated for the build, through the OR CLI, and neither capture nor the placeholder stub pattern applies to it. Verify prerequisites first (Rule 7a); missing package guide means below minimum. 7a. [UIA] Verify prerequisites beforeuia-configure-target. Follow uia-starter-guide.md § UIA Prerequisites; if package is below minimum or core guide absent,uip rpa uiais unavailable and capture/indication depend on it. Ask for installation/upgrade (§ Resolving Packages & Activity Docs, Step 1); if declined/impossible, use real placeholder activities withTODO Indicate, not another path. Indication-only is allowed only when a compatible package exists but capture cannot see the element; recordUI capture: indication-onlyin the plan header. Persistent scan failures require ruling out locked/noninteractive Windows (LogonUImeans unlock first); only after failure on an unlocked interactive session use placeholders. - Use
--output jsonwhenever CLI output is parsed programmatically. 8a. Arun/debug startverdict comes fromData— NEVER from the outerResultalone, and NEVER from a log line's level. Identify backend by keys. Headless Helm:Data={output, hasErrors, errorMessage, profiling, debugState, debugDetails, errorScope}; pass only withhasErrorsfalse,errorMessagenull, anddebugStatenull or"Completed". Faultedrunhas outerResult: "Failure"with JSON fields inMessage; faulteddebug startreturnsResult: "Success",debugState: "Suspended", and exception indebugDetails; cancel or continue the live session. Studio Desktop:Data={output, errors, logEntries, debugState}; pass only whenerrorsis empty andoutputis"Session ended". Missing entry point can returnResult: "Success", empty errors, andoutput: "Failed to open the file <path>"; require both conditions. ReadingResult: "Success"as a verdict reports broken workflows as green on both backends. Successful workflows may emit Error/Warning log messages; they are workflow data, not failures. Read the printed envelope: no--output-filteronrun/debug start(a filter naming a key the current backend lacks fails the call after the workflow has already run), and never| tail/| head; Helm logs precede the envelope and Desktop has longlogEntries. See cli-reference.md § Capturing the verdict, cli-reference.md § Reading run / debug results, and debugging.md § Output Format. - For leverage/reuse/shared libraries, search tenant feed — not the local filesystem, NuGet.org, or keyword-permutation loops:
uip or libraries list --limit 1000 --output-filter "<JMESPath>" --output json, repeated with--offset 1000,2000, … whilePagination.HasMoreistrue. On zero filtered results use its fallback branch, never re-keyword. Skip if an SDD records §16 “Shared libraries referenced” or the user earlier said no shared libraries. Follow tenant-library-search-guide.md. - Register every test case in
project.json→designOptions.fileInfoCollection, for both XAML/coded. Required keys, GUID format, schema,dataVariationFilePath, and codedpublishAsTestCaseare in references/testing-guide.md § project.json Registration and assets/json-template.md. - Test cases use Given-When-Then; see references/testing-guide.md § XAML Test Case Structure, whose lead routes the coded variant to
coded/operations-guide.md. - Identify triggers with
uip rpa activities find --query "<event>" --output json, readingisTriggerandtriggerType. Integration (true,"integration") must be first inMain.xamlrootSequence, never inui:TriggerScope; bindResultto workflow-scope variable and use the rest as handler.ConnectionIdis required for IS packages (Mail/GSuite/O365/Salesforce/Jira/Slack/ServiceNow/any*.IntegrationService.Activities), not Orchestrator-nativeTimeTrigger,QueueTrigger,ManualTrigger. Local (true,"local") may be root-first for a fresh job or in<ui:TriggerScope.Triggers>with handler in<ui:TriggerScope.Action>for an in-process robot; both placements are valid — choose by runtime model; no connection asset. Unknown types (for example future"scheduled") require bundled docs and user question. Do not assume placement. Existing TriggerScope content must be local; an integration trigger there is broken — flag to the user. Root content may be either, so inspecttriggerType. See trigger-pattern-guide.md for worked examples, theSchedulingModereference, the catalog of trigger activities, and the procedure for editing existingui:TriggerScopeworkflows.
Destination Preflight (Both Modes)
<!--skill-flavor:studio-web-destination:start-->Studio Web means a Solution deliverable, not a bare project. Studio Web ingests Solutions only; a bare project folder is invisible in both SW workspace tabs. Signals: “Studio Web”, “SW”, “upload to web”, “browser editor”, “cloud workspace edit”. Build normally, then hand off to uipath-solution: uip solution init <NAME> → uip solution projects import "<PROJECT_DIR>" --solutionFile <SOLUTION>.uipx → uip solution upload "<SOLUTION_DIR>". Deliver the Solution. Bare projects remain valid for local uip rpa run and Orchestrator uip rpa pack → uip rpa publish.
Execution Discipline (Both Modes)
Run to completion; do not declare work done while plan tasks remain. If docs/plans/*.md is referenced or discoverable, read its header before work and every checkpoint. Execution autonomy: autonomous means continue until every checkbox is [x] or a concrete plan Stop condition occurs. interactive or no plan means use judgment and confirm material decisions. Before reporting, re-read and enumerate unchecked boxes; continue unless a Stop condition occurred. Cost, call count, pauses, partial usability, and complexity are not Stop conditions. Plan decisions already made are authoritative. Do not AskUserQuestion about structure, file count, selector strategy, or capture approach when the plan specifies them.
Error Handling (Both Modes)
Wrap each external interaction whose failures need different handling in Try/Catch; classify bad input as BusinessRuleException (no retry, human needed) and transient faults as system exceptions (retry then escalate). Catch where handling differs, not around every activity; UI activities already wait and fail “element not found”, so do not guard them with Check App State (UIA package guide, Unnecessary Check App State). Do not blanket-wrap pure logic or leave Catch empty. Rethrow, never Throw New Exception(ex.Message), to preserve the stack trace. Before resilience work, read references/error-handling-guide.md in full.
Execution Maps (Both Modes)
Follow execution-maps-guide.md and the task's journey in execution-journeys-catalog.md for every build/edit: they fix batching into assistant turns (greenfield ≤5, brownfield ≤5; pitfalls vet turn included). Within a turn, chain dependent uip calls with && in one Bash; parallelize independent Bash/Read/Edit; split only when stdout or a mutation is required. Rule 21 off-card discovery fans out: all K finds parallel, then all K doc Reads, then all K get-default-xamls — never one activity at a time. Never batch across templates search → init, consent/AskUserQuestion, or UIA state advances/indication; the UIA guide’s per-screen gates control those.
Coded-Specific Rules
13–19. [Coded] Before any coded workflow, test case, or source file, read coded/codedworkflow-reference.md § Critical Rules — Coded in full. The same file also carries § Coded Quick Reference (file types, service-to-package mapping, templates) and § Task Navigation — Coded.
XAML-Specific Rules
16–21a, 24–25a. [XAML] The XAML critical rules live in xaml/xaml-basics-and-rules.md § Critical Rules — XAML — Rule 22's read-in-full mandate below covers them; they arrive with the file you must already read before any XAML work. The same file carries the XAML task navigation and quick reference.
22. [XAML] MUST read references/xaml/xaml-basics-and-rules.md in full before generating or editing any XAML — a plain full Read, emitted in the journey's first turn alongside the card reads (no lookup precedes it; the file holds only the mandatory content). The per-operation / per-activity catalogs (editing operations, reference examples) live in references/xaml/xaml-editing-catalog.md and load per entry only — Grep ^###, Read the entries matching the operation/activity at hand, unsure → read it. Then vet the plan against references/xaml/common-pitfalls.md before the first Write/Edit. common-pitfalls.md is a catalog of independent gotcha sections — do NOT read it end-to-end: list its headings (Grep ^## on the file — emit this in the first turn too, it needs no prior output), then in the next turn Read every section whose heading matches an activity, property, or feature in the workflow you are about to author. Unsure whether a section applies → read it. This is an authoring-time gate, not only a troubleshooting resource — consulting it first is cheaper than debugging a gotcha validate cannot see. The turn placement is fixed by the journeys of execution-journeys-catalog.md: the heading list rides in T1, the section Reads are T2, so the gate costs one turn, never a grep→Read pair per file.
23. [XAML] Never change existing expressionLanguage or targetFramework. They are immutable from Common Rule 2a and project-wide. Do not convert in place; confirm and follow environment-setup.md § Project Conversion: copy aside, fresh init, recreate all workflows, delete the copy only after user agreement.
Task Navigation
| I need to... | Mode | Read these |
|---|---|---|
| Work in Legacy | Legacy | legacy/legacy-mode-guide.md — entry point. Modern-mode rules below do not apply. |
| Plan build turns | Both | execution-maps-guide.md, read first for any build/edit, in the same message as a Grep ^## on execution-journeys-catalog.md; then Read the task's journey |
| Choose coded/XAML or hybrid | Both | coded-vs-xaml-guide.md → environment-setup.md § Designing Project Structure |
| Create a project | Both | environment-setup.md § Step 0.3 |
| Any XAML authoring/editing task (workflows, test cases, Flowchart/StateMachine/LRW, common activities, Data Fabric, IS connectors, triggers, XAML troubleshooting) | XAML | xaml/xaml-basics-and-rules.md — Rule 22 read; § Critical Rules — XAML + § Task Navigation — XAML route the rest |
| Any coded authoring/editing task (workflows, test cases, source files, IS connectors, NuGet, API discovery, coded troubleshooting) | Coded | coded/codedworkflow-reference.md — § Critical Rules — Coded + § Task Navigation — Coded route the rest |
| Data-driven testing | Both | testing-guide.md § Data-Driven Testing plus Rule 10 |
| Test Manager setup | Both | cli-reference.md § Test Manager — uip rpa tm connect / set-default-project |
| Error handling/resilience (Try/Catch, Retry Scope, BusinessRuleException, ContinueOnError, screenshot-on-error, Global Exception Handler, recover app state, transaction boundary, idempotency / avoid duplicate creates, queue vs local retry ownership) | Both | error-handling-guide.md |
| UI automation | Both | UIA package guide {PROJECT_DIR}/.local/docs/packages/UiPath.UIAutomation.Activities/ui-automation-guide.md |
| Share OR selectors/UI Library | Both | uia-policies-catalog.md § Object Repository as a Published UI Library |
| Run/debug UIA | Both | uia-policies-catalog.md § Running UI Automation Workflows |
| Drive captured controls | Both | UIA package guide § Control-Specific Interaction Patterns |
| Excel/Word/Mail/etc. | Both | .local/docs/packages/{PackageId}/, fallback references/activity-docs/{PackageId}/{closest}/ |
| Manipulate data (DataTable/LINQ, strings, RegEx, DateTime, collections, JSON) | Both | data-manipulation-guide.md |
| Inspect IS trigger lifecycle | Both | trigger-pattern-guide.md § Connection Handling and § Server-Side Filtering |
| Build/run/validate | Both | cli-reference.md — per-command catalog, do NOT read end-to-end: Grep ^## , read each command section used and § Reading run / debug results |
| Profile a slow workflow / verify UI automation correctness | Both | debugging.md § Profiling Workflow Performance |
Design/debug/run on a remote machine (Orchestrator unattended robot — Live Authoring vs Remote Run Only, remote configure/status/start/stop, --remote debug/run, file transfer, remote shell commands) |
Both | remote-session-guide.md |
| Pack/publish | Both | cli-reference.md § Pack & Publish to Orchestrator |
| Analyzer rules | Both | cli-reference.md § analyzer-rules list |
| Find tenant libraries | Both | tenant-library-search-guide.md |
| Author/publish library | Both | library-authoring-guide.md |
| Invoke PowerShell | Both | powershell-interop-guide.md |
| Data Fabric entities | Both | cli-reference.md § Data Fabric Entities |
| Project structure | Both | environment-setup.md § Project Structure Reference |
Mode Packs
XAML rules, quick reference, navigation, authoring, anatomy, and per-entry editing catalog: xaml/xaml-basics-and-rules.md and xaml/xaml-editing-catalog.md. Coded rules, quick reference, file types, service/package mapping, templates, navigation, and base classes: coded/codedworkflow-reference.md.
Resolving Packages & Activity Docs
Step 1 — Choose the version, then install
Read project.json dependencies, then list the available versions of every package the task needs in one chain (newest first):
uip rpa packages versions --package-id <PackageId> --include-prerelease --project-dir "<PROJECT_DIR>" --output json
Version choice is the user's: never install or upgrade a package silently. Before any packages install, ask one question covering every package that is absent or older than its latest stable release; a newer prerelease alone asks nothing. Per package, offer the latest stable (recommended), the latest prerelease when it is newer (previews may hold activities, signatures, and docs the stable lacks), and, for an installed package, keeping its version. Name any option that crosses a major version, since it may deprecate activities existing workflows use. A version the user named, or a plan whose tasks name each package ID and version, is the answer; do not ask again. Install the chosen versions in one call, one --packages per package:
uip rpa packages install --packages 'id=<PackageId>,version=<CHOSEN_VERSION>' --project-dir "<PROJECT_DIR>" --output json
Step 2 — Find activity docs
First directly Read {PROJECT_DIR}/.local/docs/packages/{PackageId}/activities/<Activity>.md; failed direct Read is the existence check. Glob/Grep skip gitignored .local/ and prove nothing; use ls on the exact directory to list it. Never enumerate the tree. If absent, use the closest installed-version folder under references/activity-docs/{PackageId}/.
UI Automation References
Skill references own prerequisites/version gating, run/debug orchestration, placeholder deliverables, and UI Library publishing. The installed UIA pack at {PROJECT_DIR}/.local/docs/packages/UiPath.UIAutomation.Activities/ owns authoring, capture, CLI syntax, activity properties, coded API, runtime recovery, and its bundled uia-configure-target; it is co-versioned and wins on divergence.
Read uia-starter-guide.md first for UIA. The pack’s ui-automation-guide.md is the full entry point and routes target capture, task guides, CLI inventory, activity properties, coded API, recovery, and bundled skill; verify it by exact-path ls or direct Read, never Glob/Grep.
Completion Output
Before “done”, verify plan completion: re-read docs/plans/*.md; if autonomous and unchecked boxes remain without a Stop condition, resume; if a Stop condition stopped work, name it; if interactive, report status. Save only memory patterns qualified by execution-maps-guide.md § Cross-session memory; a first-try clean gate on card-covered activities qualifies none. If persistent memory exists, write qualifying memory, context files, and report in parallel in the final turn; nothing runs afterward.
When finished, report:
<!--skill-flavor:report-what-was-done:start-->- What was done — created, edited, and deleted file paths.<!--skill-flavor:report-what-was-done:end--> <!--skill-flavor:report-validation-status:start-->
- Validation status — every touched file’s per-file
validateand project-leveluip rpa build. Both must be clean to claim verification; if build has not run since the last edit, say so.<!--skill-flavor:report-validation-status:end--> - Plan completion — checked
[x]tasks and every remaining[ ], with its Stop-condition item or “not reached”.<!--skill-flavor:report-how-to-run:start--> - How to run — applicable
uip rpa runoruip rpa debug startcommand.<!--skill-flavor:report-how-to-run:end--> - Next steps — connections, OR elements, placeholders, and other follow-up actions.
- Trouble? — if issues occurred, say: “If something didn't work as expected, use
/uipath-feedbackto send a report.”
Do not say “complete”, “done”, “finished”, or “the automation is built” unless all plan tasks are checked; otherwise say “Partial”, “stopped at <task N>”, or “blocked by <stop condition>”.
Open this reference as its own page
UiPath CLI (uip) Reference
uip rpa and sibling tools (uip is, uip tm, …) communicate with UiPath Studio over named pipes (IPC). Use this reference to discover live commands, arguments, and flags, and to handle authentication, Studio backends, run results, and recovery.
Command and flag lists are not exhaustive or current. Discover the live surface with
--help; this document covers behavior--helpomits.
Installation is automatic. Do NOT install
uipmanually or instruct the user to install it.
Discover the live CLI with --help
Append --help at any level to drill from tools to groups, verbs, and parameters. Run --help rather than guessing unknown verbs, flags, or values.
uip --help
uip tools list
uip rpa --help
uip rpa packages --help
uip rpa validate --help
uip is --help
uip skills --help
The pattern works at every depth (uip rpa uia <verb> --help, uip login --help, etc.). Run --help standalone, never with other flags: uip rpa <verb> --help --project-dir "<path>" parses the value as a positional command and returns unknown command '<value>'. A verb may be hidden from help but callable by exact name; absence means it is not part of the standard loop, not that it does not exist.
Output format
--output defaults to json; accepted values are json, table, yaml, and plain. Keep json for programmatic parsing; table can balloon to 100 KB+. --output-filter "<JMESPath>" filters the response envelope's Data field. Global --log-level <debug|info|warn|error> and --log-file <path> are available; raise the log level or add --verbose when diagnosing. Most envelopes are {Result: "Success"|"Failure", Code, Data, Message?, Instructions?}. Branch on Result, not stdout text: it says whether the command ran; what the command found is in Data (validate's diagnostics: § validate).
Authentication
Cloud features (feed templates/packages, Integration Service, Data Service entities, and publishing) require a logged-in session.
uip login
uip login status
uip login which
If a command returns not authenticated, 401, or 403, run uip login and retry. Discover non-interactive/CI credentials-folder, client-id/secret, and authority options with uip login --help.
Project context: --project-dir
Most uip rpa verbs use --project-dir, defaulting to the current directory. When elsewhere, pass the absolute folder containing project.json in long form. An 8.3 path such as C:\\Users\\ABCDEF~1\\… can make run fail at Building for execution with An item with the same key has already been added. Key: <workflow path>. init instead uses --name and --location; build and pack take the project directory positionally, so confirm each verb with --help.
To create a project, see environment-setup.md. Decide --target-framework and --expression-language before init; they are immutable afterward.
Headless Studio (Helm) vs Studio Desktop
uip rpa uses one of two backends:
- Headless Studio (Helm), default: a NuGet package auto-launches on first use; Studio Desktop is unnecessary. A cold cache may be nearly silent for 30–90 s during
dotnet restore; the default shell timeout covers this, so raisetimeoutSecondsonly behind a slow feed. - Studio Desktop: a running Desktop instance with the project open handles that project's calls, including
runanddebug start.uip rpa instances list --output jsonshows project ownership. UI-side-effect verbs work only here: ensure Desktop is up withuip rpa studio start --project-dir "<PROJECT_DIR>", then run them. Force Desktop withUIPATH_RPA_TOOL_USE_STUDIO=1(not recommended for the standard authoring loop).
The backends return different run/debug start payloads; see Reading run / debug results. --studio-dir applies only to Desktop; Helm ignores it. If Desktop detection fails, resolution falls back to UIPATH_STUDIO_DIR, the default install path, then a dev build output. Studio <VERSION> at "<STUDIO_DIR>" does not support rpa-tool. Upgrade UiPath Studio. or Requires Studio <MIN_VERSION>+, detected <VERSION>. Please upgrade UiPath Studio. means this Studio Desktop has no rpa-tool interop: Desktop-only verbs fail, Helm verbs still work (unless UIPATH_RPA_TOOL_USE_STUDIO=1 is set; unset it). Continue headless and do not ask the user to upgrade: use debug start --breakpoints instead of focus-activity + debug test-activity/start-from-here/toggle-breakpoint (debugging.md), edit the file directly instead of files diff, and write test data as files (testing-guide.md § Adding Test Data via CLI). Ask for an upgrade only when the task needs a Desktop-only verb that has no headless route.
Installed package activity documentation
Installed activity docs are under {PROJECT_DIR}/.local/docs/packages/{PackageId}/; read them directly because they expose per-activity properties and coded API signatures unavailable through --help.
| Action | How |
|---|---|
| Read an activity doc | Read …/{PackageId}/activities/{ActivityName}.md |
| Read coded API doc | Read …/{PackageId}/coded/coded-api.md |
| Read package overview | Read …/{PackageId}/overview.md |
| List packages/activities | Bash: ls …/.local/docs/packages/, then ls …/{PackageId}/activities/ |
| Search activity docs | Use Bash ls on …/.local/docs/packages/<PackageId>/activities/, then Read the matching path. Do NOT use Glob or Grep; both skip gitignored .local/, and a miss proves nothing. |
Reading run / debug results
uip rpa run executes without debugging. The debug group handles breakpoints, stepping, and exceptions; see debugging.md. Prefer debug start for UI automation so the application remains available for selector repair. Cancel an active run/session with uip rpa execution cancel. Pass workflow inputs as repeatable --input-arguments key=value pairs; see Passing structured inputs. Discover remaining flags (log level, skip-build, profiling) with --help.
Both return {Result, Code, Data}. Identify the backend from Data:
| Backend | Data keys |
Workflow Log Message output |
|---|---|---|
| Headless Studio (Helm) | output (serialized output arguments, "{}" if none), hasErrors, errorMessage, profiling, debugState, debugDetails, errorScope |
stdout lines such as [Information] … and [Error] … above the JSON envelope; none in Data |
| Studio Desktop | output (completion status "Session ended"), errors array, logEntries array of {source, level, message} where source is Compile or Debug, and debugState ("Completed" on completion; absent if the file could not open) |
Data.logEntries; nothing above the envelope |
Field meanings are in debugging.md § Output Format.
- Helm passes only when
hasErrorsisfalse,errorMessageisnull, anddebugStateisnullor"Completed". A fault, validation failure, or missing entry point returns outerResult: "Failure"with the same fields JSON-encoded inMessage(hasErrors: true,errorMessagecontaining the failure). A faulted Helmdebug startreturnsResult: "Success"withhasErrors: false,debugState: "Suspended", the exception indebugDetailsand command guidance inerrorMessage— the session is still alive; cancel or continue it. - Desktop passes only when
errorsis empty andoutputis"Session ended". A missing entry point can returnResult: "Success",errors: [],logEntries: [], andoutput: "Failed to open the file <absolute path>". Undeclared--input-argumentskeys are silently accepted with"Session ended". - Never treat outer
Result: "Success"alone as a pass or infer failure fromWarning/Errorlog levels;Log Messagecan emit any level.
Capturing the verdict
Run run / debug start with no --output-filter and read the envelope as printed. The two backends return different key sets, so a filter written for one names keys the other does not have; the CLI then rejects the whole call with Filter '…' failed to evaluate: Invalid type … received type null after the workflow has already run (length(errors) on Helm, any function on hasErrors on Desktop), and the retry re-drives the application and costs a turn. On Helm the filter cannot reach the log lines at all — they are outside Data.
uip rpa run --file-path "<FILE>" --project-dir "<PROJECT_DIR>" --skip-build --output json
Helm:
[Information] Starting execution...
[Information] <PROJECT_NAME> execution started
[Information] Sum: 10
[Information] <PROJECT_NAME> execution ended in: 00:00:00
{ "Result": "Success", "Code": "Run", "Data": {
"output": "{}", "hasErrors": false, "errorMessage": null, "profiling": null, "debugState": null, "debugDetails": null, "errorScope": null } }
Studio Desktop (same command, project open in Studio):
{ "Result": "Success", "Code": "Run", "Data": {
"output": "Session ended", "errors": [],
"logEntries": [ { "source": "Debug", "level": "Information", "message": "<PROJECT_NAME> execution started" },
{ "source": "Debug", "level": "Information", "message": "Sum: 10" },
{ "source": "Debug", "level": "Information", "message": "<PROJECT_NAME> execution ended in: 00:00:06" } ],
"debugState": "Completed" } }
Read Helm [Information] lines above the envelope without stripping them (grep -v '^\[' is wrong). Read Desktop workflow values from logEntries; Trace entries such as Unregistered service requested … and Audit: … may outnumber them. Helm debug start puts suspended-state exception details in debugState/debugDetails.
Never pipe the payload through tail -N or head -N: Helm places logs before the envelope, while Desktop places output and errors before a potentially long logEntries; recovering either requires a rerun and may change a non-rerun-safe workflow. For Helm Result: "Failure" without Data, read Message: it contains JSON-encoded Data fields (hasErrors: true) for a fault, validation failure, or missing entry point; a project that cannot open or a busy executor returns {"success": false, "errorMessage": "…"}.
When the envelope lacks enough detail, redirect all stdout with > run.log and read the file: Helm [Error] lines plus errorMessage; Desktop errors and logEntries. jq is absent on a standard Windows agent host; the envelope is the last JSON object in the file.
Passing structured inputs
--input-arguments and --input-variables accept repeatable key=value, key:=value (raw JSON), or key=@file pairs; an inline JSON string; or a JSON file via '@file' or --<flag>-file. --packages is repeatable, one item per occurrence, with comma-joined fields.
uip rpa run --file-path Main.xaml --input-arguments name=John --input-arguments retries:=3
uip rpa run --file-path Main.xaml --input-arguments 'message=Hello, world!'
uip rpa debug test-activity --input-variables greeting=@expression.txt
uip rpa run --file-path Main.xaml --input-arguments '@args.json'
uip rpa run --file-path Main.xaml --input-arguments-file args.json
uip rpa packages install --packages 'id=UiPath.System.Activities,version=23.10.1' --packages id=UiPath.Excel.Activities
Rules: count=42 sends string "42"; count:=42 sends number 42. debug test-activity and debug start-from-here require VB/C# expression strings, so always use =. Single-quote tokens containing spaces, commas, or leading @; bare identifiers/numbers need no quotes. Windows PowerShell 5.1 strips inline double quotes: write such values to a UTF-8 file with Set-Content -Encoding UTF8, then use key=@file, '@file', or --<flag>-file. Inline JSON remains accepted for backward compatibility but is unreliable on PowerShell 5.1; prefer pairs/files. key= passes an empty string and overrides a coded workflow's declared default; omit the flag to use the default.
validate
uip rpa validate returns diagnostics for a file or project and revalidates by default. --skip-validation reads possibly stale cached results; --min-severity filters. Confirm flags with uip rpa validate --help. --file-path accepts a project-relative or absolute path with forward, back, or mixed separators; prefer the shorter relative form.
Result: Success and exit code 0 mean validate found no errors; warnings may still be listed. At least one error gives Result: Failure and exit code 1 (Code: ValidationErrorsFound). In both cases the diagnostics are the text of Data.message: No diagnostics found., or Found N error(s)[, M warning(s)]: followed by one [error] or [warning] line per finding (file, message, activity).
An activity that can run without a target reports no unset target: Type Into and Keyboard Shortcuts act on the focused element by design, so validate's "Target or Input UI Element must be set" errors are not a count of a file's target slots.
Validate reads the entity types the project last generated. After a Data Fabric entity install changes the project's entities, run build: a workflow whose entity type the install removed still validates with no diagnostics, and build fails with Cannot create unknown type.
build
uip rpa build compiles every workflow in the project, not just files passed to validate (§ What each phase covers); it is required before returning a project (see § Project Build Verification). It takes the project directory positionally, runs independently of Studio IPC, and exposes log level, skip-analyze, governance, and NuGet-source flags through uip rpa build --help.
run and debug start compile internally but do not apply analyzer rules. A successful smoke test proves compilation, not build. A successful build writes entry-points.json (each entry point's argument schema) and bindings_v2.json (resources such as the queue a Get Queue Item names) under .local/content/, which pack ships, and deletes a root entry-points.json (templates ship one). Leave the root file deleted: restoring it changes nothing, and the next build deletes it again.
analyzer-rules list
uip rpa analyzer-rules list reports enabled rules, not violations. Do NOT run it as an authoring prerequisite; run it only when the user asks about analyzer/best-practice rules or recurring build violations suggest authoring against the full set. Results contain severity (error/warning/info), rule ID, scope, title, and optionally recommendation and docs. ST-* means built-in Studio; MA-* means package-shipped.
Coded Workflow rules run as Roslyn analyzers over .cs files during analyze, build, and pack, with the same enforcement as XAML rules. The four built-in rules are Error severity; see coded/operations-guide.md § Coded Workflow Analyzer Rules. The unscoped call can enumerate every package rule for a minute or more; narrow with --scope values Activity, Workflow, Project, or Coded Workflow.
packages install
uip rpa packages install is the canonical dependency operation; do not hand-edit project.json, and there is no add-dependency verb. Repeat --packages with comma-joined key=value fields (--packages 'id=<PackageId>,version=<Version>' or --packages id=<PackageId>); discover remaining flags with uip rpa packages install --help.
Omitting version resolves the latest compatible version; choose the version with the question in SKILL.md § Resolving Packages & Activity Docs, Step 1. For a missing package, verify the exact ID with activities find or .local/docs. For feed/network errors, check Studio NuGet feed configuration.
Remove unused dependencies with uip rpa cleanup "<PROJECT_DIR>" --skip-imports --output json; use --dry-run first and inspect Data.UnusedItems. Without --skip-imports, cleanup also removes unused namespace imports and resaves every workflow. No verb removes one named dependency.
object-repository
Both project-repository verbs are top-level and hyphenated, require an open project, and support standard --project-dir; there is no uip rpa object-repository group — it returns Unknown command: object-repository, Studio running or not. They differ from the UIA OR CLI, which writes entries and has no get.
uip rpa get-object-repository returns only the project's own JSON tree of applications, screens, and elements, each with name, description, type, and reference; referenced-library entries are excluded. name is an Object Repository name, not a C# member (Result Display becomes Result_Display in Descriptors.*); follow the coded authoring guide's § Descriptor Naming routed from ui-automation-guide.md § Documentation.
uip rpa get-object-repository --project-dir "<PROJECT_DIR>" --output json
uip rpa get-library-object-repository reads one or more library .nupkg files and groups returned applications, screens, and elements by library; packages without an Object Repository are omitted. --library-paths is required, accepts absolute paths comma-separated in one flag, is not repeatable, and should not contain commas.
uip rpa get-library-object-repository \
--project-dir "<PROJECT_DIR>" \
--library-paths "C:\libs\Acme.UiLib.1.2.0.nupkg,C:\libs\Other.UiLib.2.0.0.nupkg" \
--output json
Read the project repository before authoring UI Automation to reuse existing targets; read library repositories for targets exposed by referenced libraries. Confirm flags with uip rpa get-object-repository --help and uip rpa get-library-object-repository --help.
Commands -- Data Fabric Entities
Data Fabric entities in the Orchestrator tenant's Data Service must be installed into the RPA project before typed arguments, UiPath.DataService.Activities, test-data bindings, or generated entity types can be used. Installation writes .entities/ and compiles a strongly typed assembly. .entities/EntitiesStore.json holds the definitions of every entity the tenant's Data Service exposes, the installed ones marked, and the tenant's URL, and pack ships it in the package. Before publishing such a package outside the tenant (another tenant's feed, a public feed), tell the user it carries every tenant entity definition and the tenant URL. Under uip rpa data-fabric-entities, discover exact flags with --help:
- List: show entities installed in the project and available in the tenant, each with
installed; run before installing to select names or verify bindings. - Install: apply an add/remove delta. Dependencies expand automatically; server-deleted entities are dropped. Final selection is
(installed ∪ add) − remove; empty selection uninstalls the manifest.
Install entities before invoking workflows/test cases using generated types and before test-data commands binding to an entity.
Integration Service (uip is)
Discover uip is with uip is --help, then drill down (uip is connections --help, uip is resources describe --help, …). All verbs support --output json. The surface covers connectors and their activities/resources; list/create/ping/edit connections (OAuth opens a browser; --no-browser prints the URL); and CRUD resource operations. For RPA connector patterns see is-connector-xaml-guide.md.
Test Manager
Use uip tm for runtime Test Manager operations (manual cases, runs, results); discover with uip tm --help and do not invoke these runtime verbs from uip rpa. Use uip rpa tm for project configuration in .tmh/config.json; it is pure file I/O and needs no Studio or Helm process.
uip rpa tm verbs
uip rpa tm connect --url <url>setstestManagerBasePath; switching server host/org/tenant clearsdefaultProject.uip rpa tm set-default-project --id <guid> [--name <name>] [--key <key>]setsdefaultProject;connectis required first.uip rpa tm clear-default-projectunlinks the default while retaining the server URL.uip rpa tm statusshows the server URL and linked project.
All take standard --project-dir and --output json:
uip rpa tm connect --url "https://cloud.uipath.com/<org>/<tenant>/testmanager_" --project-dir "<PROJECT_DIR>" --output json
uip rpa tm set-default-project --id <project-guid> --name "<project-name>" --key "<KEY>" --project-dir "<PROJECT_DIR>" --output json
uip rpa tm status --project-dir "<PROJECT_DIR>" --output json
set-default-project does not validate the ID server-side; obtain a real Test Manager project ID from Test Manager. Listing projects is unavailable here. Confirm flags with uip rpa tm --help.
Acting on reloadHint in the output
A connect, set-default-project, or clear-default-project response may contain reloadHint only when the project is open in Studio older than 26.0.197. Tell the user to close and reopen the project; the CLI cannot do it. No reloadHint means no action is needed.
Fix One Thing at a Time
When an error occurs, identify the root cause, fix only that one thing, rerun, and verify. Never bundle speculative improvements with the fix or change two things before verification.
Validation Iteration Loop
Phase 1 — per-file validate after every edit. For every file created or edited:
REPEAT:
1. uip rpa validate --file-path "<FILE>" --project-dir "<PROJECT_DIR>" --output json
2. IF validate has errors -> fix one root cause, GOTO 1
3. EXIT when validate is clean
Phase 2 — one project build per edit session.
REPEAT:
1. uip rpa build "<PROJECT_DIR>" --log-level Warn --detailed-log-path "<LOG_FILE>" --output json
2. IF build has errors:
a. <OFFENDER> and its activity are each error's FilePath and ActivityId.IdRef in <LOG_FILE>
b. uip rpa validate --file-path "<OFFENDER>" --project-dir "<PROJECT_DIR>" --output json # compile errors only; an analyzer error is re-checked by the next build
c. fix one root cause, GOTO 1
3. EXIT to Smoke Test
Per-file validate covers structural XAML, references, schema, members, enums, and expression compilation for one file. build covers every workflow, analyzer rules, and packaging. Neither replaces the other, and neither detects an attribute-form expression that silently becomes a literal; see § What each phase covers.
Target changed files with validate --file-path; build is project-scoped; its stdout names an analyzer error by its activity only, and the detailed log (--detailed-log-path) gives every error's FilePath and ActivityId — re-run validate --file-path on that file for a compile error. Each loop has a 5-attempt cap: five Phase 1 attempts per file and a separate five Phase 2 attempts. After exhaustion, present remaining errors. Counters reset for a new file, user prompt, or resumed loop.
Rules
- DO NOT stop until all errors are resolved or cannot be resolved automatically.
- DO NOT obsess over one error; if it cannot be resolved, continue and defer it with an informative step-by-step message.
- DO NOT skip validation.
- DO NOT assume edits worked without checking.
- DO NOT bundle fixes; fix one root cause, rerun, and verify.
- Warnings are non-blocking. Once
validate/build(and, where the task requires,pack/run) are clean of errors, deliver — do not investigate warnings unless the user asked or one blocks an acceptance criterion.
See § validate and § Reading run / debug results.
Project Build Verification (Required Before Returning a Project)
Every returned project must compile. A clean Phase 2 satisfies the gate; standalone verification is:
uip rpa build "<PROJECT_DIR>" --log-level Warn --output json
If it fails, apply the Phase 2 loop with one fix per iteration and a five-attempt cap. A successful run does not substitute for build because run applies no analyzer rule.
What each phase covers
Per-file validate loads the target through the workflow designer and compiles expressions. It reports these on the file it was pointed at:
| Error class | Example | Reported as |
|---|---|---|
| Unknown member name | <uix:NGetText Value="[x]" /> (correct: TextString) |
Could not load <file>: 'Cannot set unknown member '<Class>.<Prop>'' |
| Invalid enum value | ClickType="BogusValue" |
Could not load <file>: 'Failed to create a '<Prop>' from the text '<value>'' |
| Broken expression | undefinedSymbol + 1 inside a CSharpValue |
CS0103: The name '<symbol>' does not exist in the current context |
build compiles every workflow, including untouched/unvalidated files, and applies analyzer rules and packaging. A project can therefore have clean edited files but fail on another file.
Neither per-file nor project validate checks an Invoke Workflow File's arguments against the invoked workflow; build does:
| Defect | validate |
build |
|---|---|---|
| Extra argument (a key the invoked workflow does not declare) | not reported | SY-USG-016 Error: Extra argument '<name>' not found in invoked workflow. |
| Argument type mismatch | not reported | SY-USG-016 Error: Type mismatch for argument '<name>': imported type '<type>', target type '<type>'. |
| Missing argument (an argument of the invoked workflow left unbound) | not reported | SY-USG-015 Warning: Missing argument '<name>' for the invoked workflow. — the build passes |
When a step starts invoking another workflow (a helper split into its parts, a callee whose arguments changed), build the project before calling the step done. Check a missing In argument by hand: it builds, and the invoked workflow runs with the argument's default.
Neither phase catches an attribute-form expression on InArgument<Object>: Message="calcResult" becomes a literal, so validation/build/run can succeed while logging calcResult. Inspect smoke-test output; see § Smoke Test and xaml/csharp-activity-binding-guide.md § C# Expression Pitfalls.
Analyzer errors
Error-severity analyzer rules fail analyze, build, and pack; per-file validate does not report them. Fix the workflow first. If a rule cannot be satisfied, decide with the user whether to lower it or pack with analysis skipped, and record the decision.
| Rule | Fires on | Fix |
|---|---|---|
ST-SEC-007 |
A SecureString workflow argument |
Carry the credential asset name; read the secret inside the consuming scope. |
ST-SEC-008 |
A SecureString variable used outside its declaring scope |
Declare it on the Sequence directly containing both its creator and consumers. |
ST-SEC-009 |
Converting a SecureString to text (NetworkCredential(…).Password) for a plain-string property |
Read identifiers such as OAuth client or tenant IDs from a Text asset; pass request secrets as SecureString to the code step and convert inside it. |
ST-DBP-002 |
More than 20 workflow arguments | Put them in one options object/coded class. |
UI-REL-001 |
Literal idx above 2 in a strict selector |
Replace it with a stable attribute by reconfiguring the target (SKILL.md Rule 7). |
Expected non-defect warnings
build prints [WARN] lines for enabled analyzer rules. These are not build failures and do not gate delivery (§ Validation Iteration Loop, Rule 6), except the naming warnings SKILL.md Common Rule 4c clears. Recurring ones that are correct-by-design and must not be "fixed": <activity> does not have the verification feature enabled (no matching enabled rule; VerifyOptions is deliberately off by default; add only when requested, per the UIA package guide's § Execution Verification Policy); Your organization requires your project to have an Automation Hub URL defined (ST-USG-034, organization governance resolved by the project owner in Project Settings); display-name warnings (ST-NMG-004, ST-MRD-002) on names the user dictates (xaml-basics-and-rules.md Rule 25a); and Potential infinite loop detected in Flowchart <name> starting with activity <node> (ST-REL-006), which every Flowchart with a back link raises, a bounded retry included: check that each cycle has a counter or a state change that ends it, then leave it. For an unfamiliar warning rule ID, run analyzer-rules list --scope <scope> only when it blocks an acceptance criterion.
Smoke Test
Clean validate and build are not runtime proof: attribute literals, activity CacheMetadata failures, and logic defects may appear only at runtime. After zero validation errors and a clean project build, run the workflow and inspect its output. Use --skip-build only when no edits occurred after the successful build; it executes the existing artifact and silently ignores later edits.
uip rpa run --file-path "<FILE>" --skip-build --output json
uip rpa run --file-path "<FILE>" --skip-build --input-arguments key=value --output json
uip rpa run --file-path "<FILE>" --skip-build --log-level Verbose --output json
Use bare run after edits. For coded workflows, do not pair build with a default run/debug start: build deletes .local/.codedworkflows/WorkflowRunnerService.cs, causing default execution to fail CS0246 'WorkflowRunnerService' does not exist in the namespace. Use build → run/debug start --skip-build, or a bare run/debug start.
When to run:
- Workflow has no compilation errors but you want to verify runtime behavior
- Workflow involves file I/O, API calls, or data transformations that could fail at runtime
- User specifically asks to test the workflow
When NOT to run:
- Workflow has side effects (sends emails, modifies databases, calls external APIs) -- warn the user first
- Workflow requires interactive input (UI automation, attended triggers)
- Compilation errors still exist (fix those first)
For runtime errors, analyze output, apply the one-fix rule, and retry. Stop after 2 failed runtime retry attempts and present:
Workflow execution failed after 2 retry attempts.
**Error Details:** <specific error message and location>
**Suggested Fix:** <analysis of what went wrong>
**Next Steps:** Would you like me to:
A) <recommended fix approach>
B) <alternative approach>
C) <user-driven approach>
RPA-Specific Fix Procedures
Resolving Dynamic Activity Custom Types
Dynamic activities retrieved with uip rpa activities get-default-xaml and --activity-type-id may use JIT-compiled custom property types. After adding one, read the schema to discover CLR property types for Assign targets or variables:
Read: file_path="{projectRoot}/.project/JitCustomTypesSchema.json"
Focus Activity for Debugging
When validate identifies an activity by IdRef or DisplayName, use focus-activity to highlight it in Studio Desktop. focus-activity is Desktop-only. Before invoking it, ensure Studio Desktop is up via uip rpa studio start --project-dir "<PROJECT_DIR>" (see environment-setup.md § Edge case: requiring Studio Desktop). Skip this step entirely on headless-only setups — validate already includes the IdRef and file:line in its output, which is enough to locate the activity.
# Focus a specific activity by its IdRef (from the error output):
uip rpa focus-activity --activity-id "Assign_1"
# Focus all activities sequentially (useful for walkthrough):
uip rpa focus-activity
Use it to show the user's problematic context, show a modified activity, or disambiguate an error.
Pack & Publish to Orchestrator
This section covers standalone projects only. Solution .uipx upload/publish/deploy belongs to the uipath-solution skill.
| Goal | Path | Reference |
|---|---|---|
| Orchestrator process, Test Manager automation, or library sharing | Pack → Publish | This section § Pack → Publish |
| Studio Web editing/visualization | Solution upload | uipath-solution skill |
| Packed solution deployment lifecycle | Solution publish | uipath-solution skill |
Pack → Publish (Orchestrator package flow)
Pack then publish:
uip rpa pack "<PROJECT_DIR>" "<OUTPUT_DIR>" --output json
uip rpa publish "<NUPKG_PATH>" --output json
<PROJECT_DIR> is positional 1 and contains project.json; <OUTPUT_DIR> is positional 2, must exist, and must be outside the project tree. pack refuses an in-tree output. Common optional flags (run uip rpa pack --help for the full set): --package-version <SEMVER> pins the version (otherwise project version); --skip-analyze skips the workflow-analyzer pass; use it only for known-clean builds or for a rule the user chose to skip (§ Analyzer errors); --governance-file-path <PATH> applies governance. Capture JSON PackagePath (not merely OutputPath) for publishing. pack accepts neither --project-path nor --project-dir.
publish takes a package, never a project folder. Without a destination flag it uses the package type: process/test to the tenant Processes feed, library to tenant Libraries. Success returns Data.Destination (TenantFeed, PersonalWorkspace, FolderFeed, SharedLibraries), Data.Feed, and Data.FeedId. Pass at most one destination:
--personal-workspace: personal workspace feed; processes only and also creates the process.--folder-path <PATH>/--folder-key <UUID>: a folder feed; without one,Folder '<PATH>' has no associated package feed.--shared-libraries: host shared libraries; without one,No accessible shared (host) libraries feed was found.--feed-id <UUID>: the specified feed.
Invalid package/destination combinations are refused before upload with The selected destination does not accept <Type> packages. and Instructions lists the destinations that do — re-run with one of them. A library or test package sent to --personal-workspace is refused this way. The Orchestrator package ID is project name, shown as Id by uip or packages list --output json; uip tm testcases link-automation uses it as --package-name, while uip or processes create uses it as --package-key with --package-version.
A test package includes only test cases whose project.json fileInfoCollection entry has "editingStatus": "Publishable". With none, upload fails A testing project should contain at least one entry point. (errorCode 2006). Marking cases Publishable is the user's decision; see testing-guide.md § project.json Registration. There is no uip or packages publish; use uip rpa publish.
Publishing is not running. Before offering to also schedule or run the published process, check that the target folder has a runtime to run it: uip or folders runtimes "<FOLDER>" --output json (a row with Total 0 for the runtime type means no robot can run it). Tell the user which stages (publish, trigger, run) can complete before you publish; the uipath-platform skill's end-to-end readiness guide has the full check. Report a stage done only after reading it back.
Discovery cheatsheet
uip or folders list --output json
uip or packages list --output json
The folder Key is the UUID and Path is the human path. Either is accepted by --folder-path/--folder-key; most other calls require the UUID. For Pack → Publish → Link → Execute to Test Manager, delegate to the uipath-test skill.
Common pitfalls
uip solution publish expects a packed .zip, so run uip solution pack first, then uip solution publish "<ZIP_PATH>"; standalone projects use uip rpa publish. solution upload targets Studio Web, while solution publish targets the packed solution feed and later solution deploy; they are not interchangeable. Re-publishing an existing <id>:<version> returns 409 Conflict - {"message":"Package already exists.","errorCode":1004}; bump --package-version or project.json projectVersion. If pack succeeds but analyzer output contains errors, warnings may be the cause; run uip rpa analyze "<PROJECT_DIR>" (project directory positional) when a clean signal is needed.
CLI Error Recovery
Diagnose the category, apply recovery, and retry once; do not loop the same failing command.
| Error | Cause | Recovery |
|---|---|---|
connection refused, EPIPE, pipe not found |
IPC unavailable; Helm restore/process failure or Desktop stopped | Rerun; Helm relaunches. If persistent, raise --timeout and inspect Helm restore/NuGet errors. Run uip rpa studio start only for Desktop-only verbs or UIPATH_RPA_TOOL_USE_STUDIO=1. |
timeout, ETIMEDOUT |
Cold 30–90 s Helm restore or long operation | Raise shell timeoutSeconds toward its documented maximum and uip rpa --timeout <timeoutSeconds − 30> <command>; shell timeout must exceed CLI timeout by ≥ 30 s, or the shell kills the CLI before it can cancel cleanly. For validate, try --skip-validation. |
not authenticated, 401, 403 |
Cloud authentication required | Run uip login, then retry. |
package not found, version not available |
Wrong ID/version | Verify with uip rpa activities find; omit version to auto-resolve latest. |
project not found, no project open |
Wrong path or unopened project | Verify --project-dir contains project.json; if it persists, uip rpa project open --project-dir "<PROJECT_DIR>". For Desktop-only verbs inspect hidden uip rpa instances list --output json and run uip rpa studio start if needed. |
not in the project folder in validate |
Absolute path/separator mismatch | Use a project-relative --file-path (see validate). |
Studio is busy, operation in progress |
Prior request still processing | Wait a few seconds, then retry. |
| Unrecognized error | Unknown | Rerun with --verbose, then inform the user. |
RPA discovery tools (non-CLI)
| Action | How |
|---|---|
| Explore project files | Glob **/*.xaml |
| Search XAML | Grep regex across .xaml |
| Explore Object Repository | uip rpa get-object-repository or uip rpa get-library-object-repository; alternatively Glob **/* under {PROJECT_DIR}/.objects/ and Read metadata |
| Get JIT types | Read {PROJECT_DIR}/.project/JitCustomTypesSchema.json |
| Activity docs | Installed package activity documentation |
| Inspect NuGet API | uip rpa packages inspect; see coded/codedworkflow-reference.md § Inspect NuGet Package Tool |
UI Automation (uip rpa uia ...)
uip rpa uia --help deliberately exposes no standard subcommands; the UiPath.UIAutomation.Activities package owns and versions this surface. Start from {PROJECT_DIR}/.local/docs/packages/UiPath.UIAutomation.Activities/ui-automation-guide.md (Rule 7), whose CLI-discovery section routes to task guides and the command inventory. Discover per-command flags with <discovered command> --help.
Open this reference as its own page
Coded vs XAML Decision Guide
When to use coded workflows (C#), XAML workflows (low-code), Coded Source Files, or InvokeCode — and how they interact in hybrid projects.
Mode is a per-workflow choice, not a project setting
uip rpa init produces a mode-agnostic project — both project.uiproj and project.json are scaffolded, and the project can host coded workflows (.cs), XAML workflows (.xaml), or both. The coded vs XAML decision happens when you add a workflow to the project (or when an existing project's dominant mode dictates the default — see step 1 below).
Decision Flowchart
Follow top-down. Stop at the first match.
- Did the user specify a mode? ("coded workflow", "XAML workflow", "create a .cs file", "low-code") → Use what they asked for. Do not second-guess.
- Check the project's existing mode. Match it unless there is a clear reason not to:
- XAML-only project → default to XAML. Only go coded if steps 3-6 below apply.
- Coded-only project → default to coded. Activities (Excel, Mail, UI automation) are available via services on
CodedWorkflow. - Hybrid project → either mode is fine; pick the one that fits the task best using steps 2-7.
- New project → default to XAML. "Create a workflow", "automate X", "build an automation" all mean XAML. Continue to step 2 ONLY if the user used a coded-specific phrase ("coded workflow", ".cs", "C# workflow") or named a coded-specific trigger (data models, unit tests on business logic, complex algorithmic logic). Otherwise stop here and use XAML.
- Can existing activities handle the task directly? (read Excel, send email, move file, UI click/type, queue processing, connector calls) → XAML. This covers the bulk of RPA work. No coded mode needed.
- Does it define data models, DTOs, enums, or custom classes? → Coded Source File (plain
.cs, noCodedWorkflowbase). XAML cannot define types — this is the one case where going hybrid is always justified. - Does it involve complex algorithmic logic? (5+ nested branches, LINQ aggregation, regex extraction, REST API pagination/retry, sorting/dedup/fuzzy matching) → Coded Workflow for that step. Standard if/else, simple loops, and connector calls are fine in XAML — only escalate when a single XAML workflow grows past ~50 activities.
- Does it need unit tests or assertions on business logic? → Coded Workflow + Coded Test Case for the logic under test. UI/integration tests can stay XAML.
- Is it reusable utility code? (helpers, formatters, validators, extension methods) → Coded Source File.
- Default → XAML.
Use Coded Workflows When
Custom data models — You need classes with properties to represent business entities (
InvoiceLineItem,CustomerRecord). Without coded source files, you're stuck withDataTableorDictionary<string, object>and lose type safety.// Coded Source File: OrderModels.cs public class OrderLine { public string ProductId; public decimal Price; public int Qty; }Complex data transformation — JSON deserialization into typed objects, CSV parsing with conditional logic, LINQ aggregation, regex extraction. Coded gives you full
System.Text.Json, LINQ, and string interpolation without nested InvokeCode activities.Heavy branching logic — Nested if/else-if chains, switch statements with 5+ cases, loops with
break/continue. XAML flowcharts become unreadable past 3-4 decision nodes.REST API integrations — Building HTTP requests, handling pagination, managing auth tokens with retry logic.
HttpClientpatterns in C# are far cleaner than chaining HTTP Request + Deserialize JSON activities.Reusable utility libraries — Date formatting, validation helpers, encryption, file path manipulation. Define as a Coded Source File, callable from any workflow.
Unit-testable business logic — Pure functions (input → output, no UI) that need automated assertions. Coded Test Cases can call coded workflows directly.
Algorithm-heavy work — Sorting, deduplication, fuzzy matching, tree traversal — anything that would require dozens of Assign + If activities in XAML.
Use XAML Workflows When
XAML is the default for any RPA task that does not explicitly require coded. The list below covers the typical cases — but if a task is ambiguous, the answer is XAML.
Standard business automation — Excel, email, PDF, web forms, file ops, SAP, Salesforce, ServiceNow, and other connector-driven work. The pre-built activity packages handle authentication, pagination, and error handling out of the box.
UI automation — Click, type, scrape, verify on desktop or web. XAML is the default for UI automation; the visual selector builder, recording, and indication tools are built around it. Coded UI automation via
uiAutomationservice exists but is the niche path, not the default.Simple linear processes — Read Excel → filter rows → send email → move file. Straight pipelines of 5-10 activities with minimal branching read better as XAML.
Process orchestration — REFramework, queue-based transaction processing, retry patterns. The XAML templates for these are battle-tested.
Mixed workloads — When some steps are activity-heavy and others involve light logic. Use XAML for orchestration; extract only the genuinely complex logic into a coded workflow invoked via
Invoke Workflow File.
InvokeCode: When to Extract
InvokeCode embeds C#/VB code inline in a XAML activity. It works for small snippets but becomes a maintenance problem quickly.
Extraction Rules
- Code exceeds ~15 lines → extract to a Coded Source File (utility) or Coded Workflow (if it needs
CodedWorkflowservices). - Code defines classes or types → extract to a Coded Source File. InvokeCode cannot define reusable types.
- Same code is copy-pasted across multiple XAML files → extract to a Coded Workflow and invoke it via
Invoke Workflow File. - Code needs unit tests → extract to a Coded Workflow + Coded Test Case.
- Code uses complex .NET APIs (HttpClient, LINQ, JSON serialization) → extract to a Coded Workflow for better readability and error handling.
Comparison Table
| Criterion | InvokeCode | Coded Source File | Coded Workflow |
|---|---|---|---|
| Where it lives | Inline in XAML activity | Standalone .cs file |
.cs file |
| Inherits CodedWorkflow | No | No | Yes |
Access to services (excel, mail, etc.) |
No | No | Yes |
| Can define classes/types | No | Yes | No (one class per file, must be workflow) |
| Reusable across workflows | No (copy-paste) | Yes (import namespace) | Yes (invoke from any workflow) |
| Unit testable | No | Indirectly | Yes (via Coded Test Case) |
| Recommended max size | ~15 lines | No limit | No limit |
| Entry point in project.json | N/A | No | Process only |
Hybrid Project Patterns
Hybrid projects mix coded and XAML files. The workflows property provides strongly-typed access to all workflows — both .cs and .xaml — so there is no friction in cross-invocation.
Interop Mechanisms
| From | To | Mechanism | Notes |
|---|---|---|---|
| XAML | Coded Workflow | Invoke Workflow File (path to .cs file) |
Arguments via In/Out parameters |
| Coded | XAML Workflow | workflows.XamlName() |
Strongly typed, same as coded-to-coded |
| Coded | Coded Workflow | workflows.Name() |
Strongly typed |
| Any | Any (dynamic) | RunWorkflow("path", dict) |
String-based fallback — use only when path is determined at runtime |
XAML invoking a coded workflow: each argument's x:Key is the name the coded signature produces — never an out_*/in_* XAML-style name. Name and direction rules: coded/operations-guide.md § Add a Workflow File to Existing Project, step 3.
Pattern 1: XAML Root + Coded Logic
XAML handles sequencing and simple activities. Coded workflows handle complex business logic. Coded Source Files define shared data models.
OrderProcessing/
├── project.json
├── Main.xaml # XAML: orchestrates the full process
├── ScrapeOrderPortal.xaml # XAML: UI automation with selectors
├── SendConfirmationEmail.xaml # XAML: Mail activities (straightforward)
├── ValidateAndTransform.cs # Coded workflow: 12 validation rules + LINQ transforms
├── OrderModels.cs # Coded source file: Order, LineItem, ValidationResult
└── TransformHelpers.cs # Coded source file: date parsing, currency conversion
When to use: The process has a clear linear flow (orchestrate in XAML) but contains pockets of complex logic (coded workflows) and needs typed data models (coded source files).
Pattern 2: Coded Root + XAML for Activities
Coded workflow drives the process. XAML workflows wrap activity-heavy steps that are simpler to express visually.
InvoiceProcessor/
├── project.json
├── Main.cs # Coded: orchestrates, calls all steps
├── ExtractInvoiceData.cs # Coded: PDF parsing + JSON deserialization
├── PostToSAP.xaml # XAML: SAP connector activities
├── GenerateReport.xaml # XAML: Excel activities (write range, format, save)
├── InvoiceModels.cs # Coded source file: Invoice, LineItem DTOs
└── TestExtractInvoice.cs # Coded test case
When to use: The core logic is algorithmic (coded) but some steps are best expressed with pre-built activity packages (SAP, Excel).
Pattern 3: Shared Data Models
Coded Source Files define typed models that both XAML and coded workflows use via arguments.
// OrderModels.cs — Coded Source File (no CodedWorkflow, no entry point)
namespace OrderProcessing
{
public class Order
{
public string OrderId { get; set; }
public string CustomerName { get; set; }
public List<LineItem> Items { get; set; }
public decimal Total => Items?.Sum(i => i.Price * i.Quantity) ?? 0;
}
public class LineItem
{
public string ProductId { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
}
}
Both XAML workflows (via typed arguments) and coded workflows (via direct reference) can use these types, eliminating DataTable column-name guessing and Dictionary key typos.
Anti-Patterns
- 50+ lines of C# in InvokeCode. Extract to a Coded Source File or Coded Workflow.
- Using
RunWorkflow("path")whenworkflows.*is available. Theworkflowsproperty is strongly typed and works for both.csand.xamlfiles. - Duplicating logic in both XAML and coded form. Pick one, invoke it from the other.
- Using
DataTableorDictionary<string, object>when a typed class would prevent errors. Create a Coded Source File with a proper class. - Defaulting to coded for ambiguous requests. "Create a workflow", "automate X", "build a process" mean XAML. Switch to coded only on explicit coded phrasing or a coded-specific trigger (custom types, complex algorithms, unit tests on business logic).
- Overriding the user's explicit choice. If the user says "coded workflow", create a coded workflow — do not suggest XAML instead. Same the other way: if the user says "XAML", do not suggest coded.
- Picking coded for UI automation by default. UI automation defaults to XAML. Coded UI automation via the
uiAutomationservice is the exception, not the rule.
Related References
- coded/operations-guide.md — How to create coded workflows, test cases, and source files
- coded/operations-guide.md § Coding Guidelines — C# coding rules and common issues
- xaml/xaml-basics-and-rules.md — XAML authoring workflow, anatomy, and editing
- xaml/common-pitfalls.md — InvokeCode language property gotcha
- environment-setup.md § Designing Project Structure — Project layout examples including hybrid
Open this reference as its own page
Common Activity Card
Package anchor: UiPath.System.Activities 26.4 (verified against 26.4.1-preview).
Copy-safe snippets for the 14 activities: Sequence · If · Switch<T> · TryCatch · While · DoWhile · ForEach<T> · Assign · MultipleAssign · LogMessage · WriteLine · Delay · Throw · Rethrow.
Supersedes the Rule 21 discovery procedure for these activities only: when authoring one, skip activities find, activities get-default-xaml, and the per-activity <Activity>.md read; copy its snippet here. For every other activity, full Rule 21 applies. Self-extending this card by personal judgment ("this one feels simple, I'll skip the procedure") is the failure mode.
How to read the snippets
Insert fragments in a complete <Activity> root declaring:
xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="http://schemas.uipath.com/workflow/activities"
Entries that need additional prefixes (xmlns:s for System types, xmlns:sc for System.Collections) call them out in the entry's Class: line.
Use assembly=System.Private.CoreLib for modern Windows-target projects and assembly=mscorlib for Legacy (.NET 4.6.1). Add sap2010:WorkflowViewState.IdRef to every inserted activity element per xaml/xaml-basics-and-rules.md Rule 25: <TypeName>_<next free N>; never change existing IdRefs. ViewState is optional for Sequence (Rule 20), but required when the parent is Flowchart, StateMachine, or ProcessDiagram.
Snippets use property-element <VisualBasicValue> / <VisualBasicReference>. For C# expression projects, apply xaml/csharp-activity-binding-guide.md. Unless stated otherwise, use the standard activities namespace without ui: and wrap activity body/branch slots in Sequence per Rule 24, including single-child slots.
Group A — Control flow
Sequence
Class: System.Activities.Statements.Sequence; standard activities namespace; no ui: prefix.
<Sequence DisplayName="Sequence"><!-- child activities in execution order --></Sequence>
Use Sequence as the Rule 24 container in every body/branch slot of If, Switch, TryCatch, While, DoWhile, ForEach, Pick, etc., including a single child. Declare <Sequence.Variables> only for variables it owns.
Long-form: activity-docs/UiPath.System.Activities/26.4/activities/Sequence.md
If
Class: System.Activities.Statements.If; standard activities namespace; no ui: prefix.
<If DisplayName="If"><If.Condition><InArgument x:TypeArguments="x:Boolean"><VisualBasicValue x:TypeArguments="x:Boolean" ExpressionText="counter < 10" /></InArgument></If.Condition><If.Then><Sequence DisplayName="Then"><!-- then branch --></Sequence></If.Then><If.Else><Sequence DisplayName="Else"><!-- else branch --></Sequence></If.Else></If>
Wrap both slots in Sequence; omit unused <If.Else> and never emit an empty slot. For multiple else if, use IfElseIfV2 (off this card; see ElseIf.md).
Hide Else: XAML has no property for Else visibility; Studio derives it from If.Else. Omit <If.Else> and the If opens with Else hidden (the classic designer offers a Show Else link). An empty Sequence in If.Else still shows as an empty Else drop zone in the compact designer, so it does not hide Else. A non-empty Else always opens visible: the designer's Show Else / Hide Else toggle is not saved. To hide an unused Else, omit <If.Else>; never delete activities to hide the branch.
Long-form: activity-docs/UiPath.System.Activities/26.4/activities/If.md
Switch<T>
Class: System.Activities.Statements.Switch1; standard activities namespace; no ui:` prefix.
Typed Int32 example; change x:TypeArguments as needed:
<Switch x:TypeArguments="x:Int32" DisplayName="Switch"><Switch.Expression><InArgument x:TypeArguments="x:Int32"><VisualBasicValue x:TypeArguments="x:Int32" ExpressionText="status" /></InArgument></Switch.Expression><Sequence x:Key="1" DisplayName="Case 1"><!-- case body for status == 1 --></Sequence><Sequence x:Key="2" DisplayName="Case 2"><!-- case body for status == 2 --></Sequence><Switch.Default><Sequence DisplayName="Default"><!-- fallback body --></Sequence></Switch.Default></Switch>
Wrap every case and default in Sequence. Put each literal key directly on its child with x:Key; do not declare a Cases dictionary. For strings use x:TypeArguments="x:String" and x:Key="someString".
Long-form: activity-docs/UiPath.System.Activities/26.4/activities/Switch.md
TryCatch
Class: System.Activities.Statements.TryCatch; standard namespace plus xmlns:s="clr-namespace:System;assembly=System.Private.CoreLib" for exception types; Legacy uses assembly=mscorlib.
<TryCatch DisplayName="Try Catch"><TryCatch.Try><Sequence DisplayName="Try"><!-- guarded body --></Sequence></TryCatch.Try><TryCatch.Catches><Catch x:TypeArguments="s:Exception"><ActivityAction x:TypeArguments="s:Exception"><ActivityAction.Argument><DelegateInArgument x:TypeArguments="s:Exception" Name="exception" /></ActivityAction.Argument><Sequence DisplayName="Catch"><!-- handler body; reference "exception" --></Sequence></ActivityAction></Catch></TryCatch.Catches><TryCatch.Finally><Sequence DisplayName="Finally"><!-- finally body --></Sequence></TryCatch.Finally></TryCatch>
Wrap Try, every Catch.Action, and Finally in Sequence. Each Catch requires its own <ActivityAction x:TypeArguments="..."> holding a <DelegateInArgument x:TypeArguments="..." Name="exception" />; Name is the handler variable. Put specific exception types before s:Exception; omit unused Finally. For exception taxonomy, Retry Scope, ContinueOnError, screenshot-on-error, and Global Exception Handler see error-handling-guide.md.
Long-form: activity-docs/UiPath.System.Activities/26.4/activities/TryCatch.md
While
Class: UiPath.Core.Activities.InterruptibleWhile (Studio emits this, not System.Activities.Statements.While); xmlns:ui="http://schemas.uipath.com/workflow/activities".
<ui:InterruptibleWhile DisplayName="While"><ui:InterruptibleWhile.Condition><VisualBasicValue x:TypeArguments="x:Boolean" ExpressionText="counter < 10" /></ui:InterruptibleWhile.Condition><ui:InterruptibleWhile.Body><Sequence DisplayName="Body"><!-- iteration body --></Sequence></ui:InterruptibleWhile.Body></ui:InterruptibleWhile>
MaxIterations is InArgument<int>; 0 means unlimited and is the default. Set to a positive value to guard against infinite loops. CurrentIndex is OutArgument<int>, zero-based, and may bind to a variable. Wrap the body in Sequence. The condition runs before each iteration; false on entry means no execution.
Long-form: activity-docs/UiPath.System.Activities/26.4/activities/While.md
Do While
Class: UiPath.Core.Activities.InterruptibleDoWhile (Studio emits this, not System.Activities.Statements.DoWhile); xmlns:ui="http://schemas.uipath.com/workflow/activities".
<ui:InterruptibleDoWhile DisplayName="Do While"><ui:InterruptibleDoWhile.Body><Sequence DisplayName="Body"><!-- iteration body --></Sequence></ui:InterruptibleDoWhile.Body><ui:InterruptibleDoWhile.Condition><VisualBasicValue x:TypeArguments="x:Boolean" ExpressionText="counter < 10" /></ui:InterruptibleDoWhile.Condition></ui:InterruptibleDoWhile>
MaxIterations is InArgument<int>; 0 means unlimited and is the default. CurrentIndex is OutArgument<int> and zero-based. Wrap the body in Sequence. The body executes at least once; the condition runs afterward.
Long-form: activity-docs/UiPath.System.Activities/26.4/activities/DoWhile.md
For Each<T>
Class: UiPath.Core.Activities.ForEach1(Studio emits this, notSystem.Activities.Statements.ForEach<T>); xmlns:ui="http://schemas.uipath.com/workflow/activities"`; add xmlns:sc="clr-namespace:System.Collections;assembly=System.Private.CoreLib" for non-generic IEnumerable (Legacy uses assembly=mscorlib).
Typed String example; change the outer, ActivityAction, and DelegateInArgument x:TypeArguments together:
<ui:ForEach x:TypeArguments="x:String" DisplayName="For Each"><ui:ForEach.Values><InArgument x:TypeArguments="sc:IEnumerable"><VisualBasicValue x:TypeArguments="sc:IEnumerable" ExpressionText="myList" /></InArgument></ui:ForEach.Values><ui:ForEach.Body><ActivityAction x:TypeArguments="x:String"><ActivityAction.Argument><DelegateInArgument x:TypeArguments="x:String" Name="item" /></ActivityAction.Argument><Sequence DisplayName="Body"><!-- iteration body; reference "item" --></Sequence></ActivityAction></ui:ForEach.Body></ui:ForEach>
Values is InArgument<System.Collections.IEnumerable>, not IEnumerable<T> (verified against ForEachBase<T>.Values); T comes from the outer activity. Body is ActivityAction<T> and must use <ui:ForEach.Body> (it is NOT the ContentProperty); placing a bare <ActivityAction> directly inside <ui:ForEach> produces Cannot set unknown member '...Implementation'. MaxIterations is InArgument<int> (0 = unlimited, default 0); CurrentIndex is OutArgument<int> and zero-based. The iterator name is DelegateInArgument.Name (auto-suggested by Studio based on element type); wrap the body in Sequence.
Long-form: activity-docs/UiPath.System.Activities/26.4/activities/ForEach.md
Group B — Data + logging
Assign
Class: System.Activities.Statements.Assign — no activity type argument; type its arguments. Standard namespace; no ui: prefix.
<Assign DisplayName="Assign"><Assign.To><OutArgument x:TypeArguments="x:Int32"><VisualBasicReference x:TypeArguments="x:Int32" ExpressionText="counter" /></OutArgument></Assign.To><Assign.Value><InArgument x:TypeArguments="x:Int32"><VisualBasicValue x:TypeArguments="x:Int32" ExpressionText="counter + 1" /></InArgument></Assign.Value></Assign>
Argument typing surfaces mismatches at validate. To must be writable (variable, argument, or indexer); use VisualBasicReference/CSharpReference for it and VisualBasicValue/CSharpValue for the readable side. Use one target per Assign. In a Windows project, put two or more consecutive assignments in one Multiple Assign.
Long-form: activity-docs/UiPath.System.Activities/26.4/activities/Assign.md
Multiple Assign
Class: UiPath.Core.Activities.MultipleAssign; Windows only. Portable projects fail validate with Cannot create unknown type '{http://schemas.uipath.com/workflow/activities}MultipleAssign'; use one Assign per target there, even though installed docs include MultipleAssign.md. Prefix xmlns:ui="http://schemas.uipath.com/workflow/activities"; add xmlns:scg="clr-namespace:System.Collections.Generic;assembly=System.Private.CoreLib" (Legacy uses assembly=mscorlib).
<ui:MultipleAssign DisplayName="Multiple Assign"><ui:MultipleAssign.AssignOperations><scg:List x:TypeArguments="ui:AssignOperation" Capacity="4"><ui:AssignOperation><ui:AssignOperation.To><OutArgument x:TypeArguments="x:String"><VisualBasicReference x:TypeArguments="x:String" ExpressionText="trimmedName" /></OutArgument></ui:AssignOperation.To><ui:AssignOperation.Value><InArgument x:TypeArguments="x:String"><VisualBasicValue x:TypeArguments="x:String" ExpressionText="fullName.Trim()" /></InArgument></ui:AssignOperation.Value></ui:AssignOperation><ui:AssignOperation><ui:AssignOperation.To><OutArgument x:TypeArguments="x:String"><VisualBasicReference x:TypeArguments="x:String" ExpressionText="upperName" /></OutArgument></ui:AssignOperation.To><ui:AssignOperation.Value><InArgument x:TypeArguments="x:String"><VisualBasicValue x:TypeArguments="x:String" ExpressionText="trimmedName.ToUpperInvariant()" /></InArgument></ui:AssignOperation.Value></ui:AssignOperation></scg:List></ui:MultipleAssign.AssignOperations></ui:MultipleAssign>
AssignOperations is hidden List<AssignOperation>; each operation has one typed To and Value, target types may mix, operations run in list order, and later values may read earlier targets. A failed operation reports its value and target expressions. C# uses CSharpReference/CSharpValue in this property-element form; the package attribute form (To="[firstName]") is VB bracket syntax. Shape was verified against 26.8.2 on Windows.
Long-form: the installed package's {PROJECT_DIR}/.local/docs/packages/UiPath.System.Activities/activities/MultipleAssign.md (no bundled copy); snippet shape verified against 26.8.2 on a Windows project.
Log Message
Class: UiPath.Core.Activities.LogMessage; prefix xmlns:ui="http://schemas.uipath.com/workflow/activities"; no extra prefix (x:Object uses xmlns:x).
<ui:LogMessage Level="Info" DisplayName="Log Message"><ui:LogMessage.Message><InArgument x:TypeArguments="x:Object"><VisualBasicValue x:TypeArguments="x:Object" ExpressionText="$"Processed {count} items"" /></InArgument></ui:LogMessage.Message></ui:LogMessage>
Level is InArgument<LogLevel>, required in practice, defaults to Info, and is hidden from get-default-xaml; values are Trace | Info | Warn | Error | Fatal. Message is InArgument<object>, not string; it accepts any expression and calls .ToString(). VB bracket shorthand supports composite expressions such as [$"x = {x}"]; C# uses <CSharpValue x:TypeArguments="x:Object">...</CSharpValue>. Prefer LogMessage for Orchestrator output; omit explicit Level only when Info is desired.
Long-form: activity-docs/UiPath.System.Activities/26.4/activities/LogMessage.md
Write Line
Class: System.Activities.Statements.WriteLine; standard namespace; no ui: prefix.
<WriteLine DisplayName="Write Line"><WriteLine.Text><InArgument x:TypeArguments="x:String"><VisualBasicValue x:TypeArguments="x:String" ExpressionText="$"processed {count} items"" /></InArgument></WriteLine.Text></WriteLine>
Writes to stdout only and is invisible in Orchestrator; prefer LogMessage when Orchestrator visibility matters. Do not set TextWriter; its default (Console.Out) is correct for Studio and uip rpa run.
Long-form: activity-docs/UiPath.System.Activities/26.4/activities/WriteLine.md
Delay
Class: System.Activities.Statements.Delay; standard namespace plus xmlns:s="clr-namespace:System;assembly=System.Private.CoreLib" for TimeSpan; Legacy uses assembly=mscorlib.
<Delay DisplayName="Delay"><Delay.Duration><InArgument x:TypeArguments="s:TimeSpan"><VisualBasicValue x:TypeArguments="s:TimeSpan" ExpressionText="TimeSpan.FromSeconds(5)" /></InArgument></Delay.Duration></Delay>
Duration must produce TimeSpan. VB supports [TimeSpan.FromSeconds(5)]; C# uses <CSharpValue x:TypeArguments="s:TimeSpan">TimeSpan.FromSeconds(5)</CSharpValue> or Duration="00:00:05". It blocks the workflow thread for the full duration; avoid it in ForEach/While bodies. Do not wait on external state with Delay; use RetryScope, WaitForElement, or a polling loop with a Condition.
Long-form: activity-docs/UiPath.System.Activities/26.4/activities/Delay.md
Throw
Class: System.Activities.Statements.Throw; standard namespace plus xmlns:s="clr-namespace:System;assembly=System.Private.CoreLib" for exception arguments; Legacy uses assembly=mscorlib.
<Throw DisplayName="Throw"><Throw.Exception><InArgument x:TypeArguments="s:Exception"><VisualBasicValue x:TypeArguments="s:Exception" ExpressionText="new InvalidOperationException("Invoice total is negative")" /></InArgument></Throw.Exception></Throw>
Exception is a constructor expression, not a string; Throw.Exception = "message" is invalid. Use a domain-specific type such as BusinessRuleException when Catch handlers must distinguish business from system errors. Use Rethrow inside a Catch body to preserve the original stack trace.
Long-form: activity-docs/UiPath.System.Activities/26.4/activities/Throw.md
Rethrow
Class: System.Activities.Statements.Rethrow; standard namespace; no ui: prefix.
<Rethrow DisplayName="Rethrow" />
It has zero properties and is valid only inside a Catch.Action body; elsewhere it causes runtime InvalidOperationException. It preserves the original stack trace. Use Throw new <Type>(...) to translate the exception, and place Rethrow last in the Catch body because following content is unreachable.
Long-form: activity-docs/UiPath.System.Activities/26.4/activities/Rethrow.md
Open this reference as its own page
Common Pattern Card
Package anchors: UiPath.System.Activities 26.6.1 · UiPath.Excel.Activities 3.6.0-preview (CSV) · UiPath.WebAPI.Activities 2.5.1. Every entry is CLI-verified (uip rpa validate + uip rpa build clean) on a Portable cross-platform VisualBasic project. Modern Windows-target projects use the same assembly names (System.Private.CoreLib); Legacy (.NET 4.6.1) projects are not covered.
Not on this card (Windows-only, unverifiable on the cross-platform gate): Excel X activities (ExcelProcessScopeX/ExcelApplicationCard/ReadRangeX, …) and SMTP SendMail — their docs state Platform: Windows only, and cross-platform assemblies throw TypeLoadException. Author them via the full Rule 21 triple on a Windows-target project.
Copy-safe multi-activity snippets (regeneration: .maintenance/pattern-card-maintenance.md) supersede Rule 21 discovery for every activity in a listed pattern. Otherwise use Rule 21. Card hits skip discovery, not the validate+build gate or runtime effect check for observable outputs (execution-maps-guide.md § Gate ≠ runtime proof). Precedence: card → agent memory → Rule 21 triple (execution-maps-guide.md). If validate/build rejects a card snippet, fall back to the Rule 21 triple for that activity and report the stale entry via /uipath-feedback.
Card entries
Text file read/append/write · File ops guarded copy · DataTable generate→filter→CSV · Queue publish · Retry wrap · Invoke workflow with arguments · Invoke Code bulk row processing · CSV file read/write · HTTP request → JSON
How to read the snippets
Each snippet is a complete <Sequence> fragment, including Variables, for a root <Activity> whose xmlns set matches scaffolded Main.xaml (uip rpa init output). Keep its TextExpression.NamespacesForImplementation / ReferencesForImplementation blocks.
Root prefixes:
xmlns:ui="http://schemas.uipath.com/workflow/activities"
xmlns:uic="clr-namespace:UiPath.Core.Activities;assembly=UiPath.System.Activities"
xmlns:s="clr-namespace:System;assembly=System.Private.CoreLib"
xmlns:sd="clr-namespace:System.Data;assembly=System.Data.Common"
xmlns:scg="clr-namespace:System.Collections.Generic;assembly=System.Private.CoreLib"
xmlns:csv="clr-namespace:UiPath.CSV.Activities;assembly=UiPath.Excel.Activities"
xmlns:nhr="clr-namespace:UiPath.Web.Activities.Http;assembly=UiPath.Web.Activities"
xmlns:nhrm="clr-namespace:UiPath.Web.Activities.Http.Models;assembly=UiPath.Web.Activities"
xmlns:web="clr-namespace:UiPath.Web.Activities;assembly=UiPath.Web.Activities"
xmlns:jn="clr-namespace:Newtonsoft.Json.Linq;assembly=Newtonsoft.Json"
Snippets omit sap2010:WorkflowViewState.IdRef: add one to every inserted activity element per xaml/xaml-basics-and-rules.md Rule 25, using <TypeName>_<next free N>; never change existing IdRefs. Use each entry's required prefixes and VB expression form ([expr] attributes); for C# projects see xaml/csharp-activity-binding-guide.md.
BuildDataTable (Windows-only), and by extension the DataTable group, is not registered under http://schemas.uipath.com/workflow/activities on cross-platform assemblies. The uic: clr-namespace form resolves whenever the type is loadable; file, queue, retry, and invoke activities verify under ui:.
Text file read / append / write
Activities: UiPath.Core.Activities.ReadTextFile · AppendLine · WriteTextFile · Prefixes: ui: · Variables: fileContent : String (file text); logEntry : String (line to append).
<Sequence DisplayName="Text File Read Append Write"><Sequence.Variables><Variable x:TypeArguments="x:String" Name="fileContent" /><Variable x:TypeArguments="x:String" Name="logEntry" Default="processed" /></Sequence.Variables><ui:ReadTextFile DisplayName="Read Text File" FileName="data/input.txt" Encoding="utf-8" Content="[fileContent]" /><ui:AppendLine DisplayName="Append Line" FileName="data/process.log" Text="[logEntry]" Encoding="utf-8" /><ui:WriteTextFile DisplayName="Write Text File" FileName="data/output.txt" Text="[fileContent]" Encoding="utf-8" /></Sequence>
WriteTextFile overwrites; AppendLine preserves content and creates a missing file. Encoding null means auto-detect when reading and system default when writing. FileName may be literal or [expr]. Explicit Encoding="utf-8" on WriteTextFile writes a UTF-8 BOM (EF BB BF): it passes validate+build but breaks byte-exact consumers. Omit Encoding for BOM-less output (xaml/common-pitfalls.md § WriteTextFile Emits a UTF-8 BOM).
Long-form: ReadTextFile.md · WriteTextFile.md · AppendLine: {PROJECT_DIR}/.local/docs/packages/UiPath.System.Activities/activities/AppendLine.md
File ops — guarded copy
Activities: UiPath.Core.Activities.PathExists · CreateDirectory · CopyFile (+ built-in If) · Prefixes: ui: · Variables: fileExists : Boolean.
<Sequence DisplayName="File Ops Guarded Copy"><Sequence.Variables><Variable x:TypeArguments="x:Boolean" Name="fileExists" /></Sequence.Variables><ui:PathExists DisplayName="Get Local File or Folder" Path="data/report.pdf" PathType="File" Exists="[fileExists]" /><If DisplayName="If file exists"><If.Condition><InArgument x:TypeArguments="x:Boolean"><VisualBasicValue x:TypeArguments="x:Boolean" ExpressionText="fileExists" /></InArgument></If.Condition><If.Then><Sequence DisplayName="Archive file"><ui:CreateDirectory DisplayName="Create Folder" Path="archive" /><ui:CopyFile DisplayName="Copy File" Path="data/report.pdf" Destination="archive/report.pdf" Overwrite="True" /></Sequence></If.Then></If></Sequence>
PathType="File" returns Exists=False for a directory at that path. CreateDirectory is idempotent and creates intermediate directories. Copying into an existing folder keeps the file name; a full-file destination requires its parent. MoveFile/Delete use the same Path shape.
Long-form: PathExists.md · CopyFile.md · CreateDirectory.md
DataTable — generate → add row → filter → CSV text
Activities: UiPath.Core.Activities.GenerateDataTable · AddDataRow · FilterDataTable · OutputDataTable · Prefixes: uic:, sd:, scg:, s: · Variables: dt_Data, dt_Filtered : System.Data.DataTable; csvText : String.
<Sequence DisplayName="DataTable Build Filter Output"><Sequence.Variables><Variable x:TypeArguments="sd:DataTable" Name="dt_Data" /><Variable x:TypeArguments="sd:DataTable" Name="dt_Filtered" /><Variable x:TypeArguments="x:String" Name="csvText" /></Sequence.Variables><uic:GenerateDataTable DisplayName="Generate Data Table From Text" AutoDetectTypes="True" UseColumnHeader="True" CSVParsing="True"><uic:GenerateDataTable.Input><InArgument x:TypeArguments="x:String">["Name,Age" & vbLf & "Bob,25"]</InArgument></uic:GenerateDataTable.Input><uic:GenerateDataTable.DataTable><OutArgument x:TypeArguments="sd:DataTable">[dt_Data]</OutArgument></uic:GenerateDataTable.DataTable></uic:GenerateDataTable><uic:AddDataRow DisplayName="Add Data Row"><uic:AddDataRow.DataTable><InOutArgument x:TypeArguments="sd:DataTable">[dt_Data]</InOutArgument></uic:AddDataRow.DataTable><uic:AddDataRow.ArrayRow><InArgument x:TypeArguments="s:Object[]">[New Object() {"Alice", 30}]</InArgument></uic:AddDataRow.ArrayRow></uic:AddDataRow><uic:FilterDataTable DisplayName="Filter Data Table" FilterRowsMode="Keep" OutputDataTable="[dt_Filtered]"><uic:FilterDataTable.DataTable><InArgument x:TypeArguments="sd:DataTable">[dt_Data]</InArgument></uic:FilterDataTable.DataTable><uic:FilterDataTable.Filters><scg:List x:TypeArguments="uic:FilterOperationArgument"><uic:FilterOperationArgument Operator="GT" BooleanOperator="And"><uic:FilterOperationArgument.Column><InArgument x:TypeArguments="x:String">"Age"</InArgument></uic:FilterOperationArgument.Column><uic:FilterOperationArgument.Operand><InArgument x:TypeArguments="x:Int32">[10]</InArgument></uic:FilterOperationArgument.Operand></uic:FilterOperationArgument></scg:List></uic:FilterDataTable.Filters></uic:FilterDataTable><uic:OutputDataTable DisplayName="Output Data Table as Text"><uic:OutputDataTable.DataTable><InArgument x:TypeArguments="sd:DataTable">[dt_Filtered]</InArgument></uic:OutputDataTable.DataTable><uic:OutputDataTable.Text><OutArgument x:TypeArguments="x:String">[csvText]</OutArgument></uic:OutputDataTable.Text></uic:OutputDataTable></Sequence>
Build-verified traps: BuildDataTable does NOT load on cross-platform projects (TypeLoadException); generate from CSV text instead. ParsingMethod/CSV are designer-only; the runtime member is CSVParsing="True". ArrayRow is s:Object[], never x:Object[] (common-pitfalls.md § x: prefix). Filters Operator takes enum identifiers (GT, EQ, CONTAINS, …); omit Operand for EMPTY/NOTEMPTY. AddDataRow.DataTable is InOutArgument; bind a variable, never an expression.
Long-form: GenerateDataTable.md · AddDataRow.md · FilterDataTable.md · OutputDataTable.md
Queue publish
Activities: UiPath.Core.Activities.AddQueueItem · Prefixes: ui:, s:
<ui:AddQueueItem DisplayName="Add Queue Item" QueueType="InvoiceProcessing" Priority="High" Reference="INV-2024-002" DueDate="[DateTime.Now.AddDays(1)]"><ui:AddQueueItem.ItemInformation><InArgument x:TypeArguments="x:String" x:Key="InvoiceNumber">"INV-2024-002"</InArgument><InArgument x:TypeArguments="x:Double" x:Key="Amount">1500.0</InArgument><InArgument x:TypeArguments="x:Boolean" x:Key="Approved">True</InArgument><InArgument x:TypeArguments="s:DateTime" x:Key="InvoiceDate">[DateTime.Today]</InArgument></ui:AddQueueItem.ItemInformation></ui:AddQueueItem>
Runtime requires Orchestrator and an existing queue; QueueType does not auto-create one (404 error code 1002 otherwise). The item status is New. Queue consumption (GetTransactionItem) is unavailable in cross-platform UiPath.System.Activities; see reframework-guide.md. Use s:DateTime, not x:DateTime.
Long-form: AddQueueItem.md
Retry wrap
Activities: UiPath.Core.Activities.RetryScope · Prefixes: ui:, s: · Variables: fetchedContent : String (example body output).
<ui:RetryScope DisplayName="Retry Scope"><ui:RetryScope.NumberOfRetries><InArgument x:TypeArguments="x:Int32"><VisualBasicValue x:TypeArguments="x:Int32" ExpressionText="3" /></InArgument></ui:RetryScope.NumberOfRetries><ui:RetryScope.RetryInterval><InArgument x:TypeArguments="s:TimeSpan"><VisualBasicValue x:TypeArguments="s:TimeSpan" ExpressionText="TimeSpan.FromSeconds(5)" /></InArgument></ui:RetryScope.RetryInterval><ui:RetryScope.ActivityBody><ActivityAction><Sequence DisplayName="Action"><ui:ReadTextFile DisplayName="Read flaky source" FileName="data/flaky-source.txt" Content="[fetchedContent]" /></Sequence></ActivityAction></ui:RetryScope.ActivityBody><ui:RetryScope.Condition><ActivityFunc x:TypeArguments="x:Boolean" /></ui:RetryScope.Condition></ui:RetryScope>
An empty ActivityFunc retries on exception only. To retry until true, place an Activity(Of Boolean) inside Condition. Serialize the body as ActivityBody/ActivityAction, not a bare child.
Long-form: RetryScope.md
Invoke workflow with arguments
Activities: UiPath.Core.Activities.InvokeWorkflowFile · Prefixes: ui: · Variables: childResult : String.
<ui:InvokeWorkflowFile DisplayName="Invoke Workflow File" WorkflowFileName="Pattern_Child.xaml"><ui:InvokeWorkflowFile.Arguments><InArgument x:TypeArguments="x:String" x:Key="in_Message">["hello"]</InArgument><OutArgument x:TypeArguments="x:String" x:Key="out_Result">[childResult]</OutArgument></ui:InvokeWorkflowFile.Arguments></ui:InvokeWorkflowFile>
Declare the child contract via root x:Members:
<x:Members><x:Property Name="in_Message" Type="InArgument(x:String)" /><x:Property Name="out_Result" Type="OutArgument(x:String)" /></x:Members>
Keys must exactly match declared argument names; use InArgument/OutArgument/InOutArgument according to direction. Execution is synchronous and WorkflowFileName is project-relative. XML-escape & in VB concatenation (&).
Long-form: InvokeWorkflow.md
Invoke Code — bulk row processing
Activities: UiPath.Core.Activities.InvokeCode (input DataTable from the DataTable entry) · Prefixes: ui:, scg:, sd: · Verified: UiPath.System.Activities 26.6.2 — validate + build + run (outputs checked; this is the silent-no-op activity, so the gate alone is not proof). · Variables: dt_Data : System.Data.DataTable; validCount : Int32; totalAmount : Double.
<ui:InvokeCode DisplayName="Process Rows" Language="VBNet" Code="For Each row As System.Data.DataRow In rows.Rows
 Dim amount As Double
 If Double.TryParse(row("Amount").ToString(), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, amount) AndAlso amount > 0 Then
 validCount += 1
 totalAmount += amount
 End If
Next"><ui:InvokeCode.Arguments><scg:Dictionary x:TypeArguments="x:String, Argument"><InArgument x:TypeArguments="sd:DataTable" x:Key="rows">[dt_Data]</InArgument><OutArgument x:TypeArguments="x:Int32" x:Key="validCount">[validCount]</OutArgument><OutArgument x:TypeArguments="x:Double" x:Key="totalAmount">[totalAmount]</OutArgument></scg:Dictionary></ui:InvokeCode.Arguments></ui:InvokeCode>
Use this as the default escalation for complex bulk row processing: per-row parse + validate + branch + accumulate (data-manipulation-guide.md § Code vs activity chains). A ForEach with ONE If/Switch stays plain XAML.
Run-verified traps: Code MUST be an XML attribute (
 newlines, " quotes); a child/CDATA <ui:InvokeCode.Code> loses line breaks, so a C# // comment then swallows subsequent code and a VB body fails to compile (xaml/common-pitfalls.md § InvokeCode Code Property). Set Language: CSharp in a C# project and VBNet in a VB project; without it code compiles as VB.NET (§ InvokeCode Language Property). Argument keys must match code identifiers; bind variables, not expressions, to OutArguments. Parse with InvariantCulture; bare Double.TryParse under a comma-decimal locale silently rejects 10.5-style input. C# expression projects hit expression-tree limits in surrounding XAML expressions, not inside Code, whose body is a normal method body.
Long-form: {PROJECT_DIR}/.local/docs/packages/UiPath.System.Activities/activities/InvokeCode.md
CSV file read / write
Activities: UiPath.CSV.Activities.ReadCsvFile · AppendWriteCsvFile · Packages: UiPath.Excel.Activities 3.6.0-preview (CSV activities are Excel-package-owned, cross-platform, and need no Excel app) · Prefixes: csv:, sd: · Variables: dt_Csv : System.Data.DataTable.
<Sequence DisplayName="CSV Read Write"><Sequence.Variables><Variable x:TypeArguments="sd:DataTable" Name="dt_Csv" /></Sequence.Variables><csv:ReadCsvFile DisplayName="Read CSV" FilePath="data/input.csv" IncludeColumnNames="True" DataTable="[dt_Csv]" /><csv:AppendWriteCsvFile DisplayName="Write CSV" FilePath="data/output.csv" CsvAction="Write" AddHeaders="True"><csv:AppendWriteCsvFile.DataTable><InArgument x:TypeArguments="sd:DataTable">[dt_Csv]</InArgument></csv:AppendWriteCsvFile.DataTable></csv:AppendWriteCsvFile></Sequence>
CsvAction values: Write replaces and Append adds after existing rows. Set the delimiter through DelimitatorForViewModel (Comma default; Semicolon/Pipe/Caret/Tab). IncludeColumnNames="True" makes the first row headers.
Long-form: ReadCsvFile.md (3.6) · {PROJECT_DIR}/.local/docs/packages/UiPath.Excel.Activities/activities/AppendWriteCsvFile.md
HTTP request → JSON
Activities: UiPath.Web.Activities.Http.NetHttpRequest · UiPath.Web.Activities.DeserializeJson<T> · Packages: UiPath.WebAPI.Activities 2.5.1 · Prefixes: nhr:, nhrm:, web:, jn: · Variables: httpResponse : UiPath.Web.Activities.Http.Models.HttpResponseSummary; jsonResult : Newtonsoft.Json.Linq.JObject.
<Sequence DisplayName="HTTP GET Deserialize"><Sequence.Variables><Variable x:TypeArguments="nhrm:HttpResponseSummary" Name="httpResponse" /><Variable x:TypeArguments="jn:JObject" Name="jsonResult" /></Sequence.Variables><nhr:NetHttpRequest DisplayName="GET API Data" RequestUrl="https://api.example.com/data" Method="GET" RequestBodyType="None" RetryPolicyType="Basic" RetryCount="[3]" TimeoutInMiliseconds="[10000]" Result="[httpResponse]" /><web:DeserializeJson x:TypeArguments="jn:JObject" DisplayName="Deserialize JSON" JsonString="[httpResponse.TextContent]" JsonObject="[jsonResult]" /></Sequence>
Use NetHttpRequest, not legacy HttpClient. The XAML assembly is UiPath.Web.Activities, not package id UiPath.WebAPI.Activities; HttpResponseSummary is in ...Http.Models. Read the body from httpResponse.TextContent and evaluate the response with httpResponse.StatusCode. Default ContinueOnError=True turns network failures into synthetic 503 responses; guard on StatusCode before parsing. For POST JSON, use RequestBodyType="Text" + TextPayload; content type defaults to application/json.
Long-form: {PROJECT_DIR}/.local/docs/packages/UiPath.WebAPI.Activities/activities/NetHttpRequest.md · .../DeserializeJson.md
Open this reference as its own page
Data Manipulation Guide
Transform data outside activities: DataTable LINQ, strings, RegEx, DateTime, conversion, collections, and JSON.
Owned elsewhere: DataTable activity mechanics (BuildDataTable TableInfo trap + inline build, FilterDataTable type-compat, LookupDataTable, GetRowItem) → xaml/common-pitfalls.md § DataTable Activity Gotchas; C# XAML expression binding (CSharpValue/CSharpReference) → xaml/csharp-activity-binding-guide.md; REFramework configuration access → reframework-guide.md; activity properties (ForEachRow, AddDataRow, JoinDataTables, SortDataTable, …) → {PROJECT_DIR}/.local/docs/packages/UiPath.System.Activities/ or references/activity-docs/UiPath.System.Activities/; coded-mode using directives → coded/operations-guide.md § Using Statements Rules.
Where each snippet goes — read first
A DataTable LINQ chain is one value for one Assign. For Each, Dim, and mutation blocks are not expressions and cannot go in an Assign; statement-style VB pasted there is the most common paste error.
| Tag | Placement |
|---|---|
[expr] |
One Assign.Value, one expression. Examples are VB; translate for C#-expression projects and wrap in CSharpValue; VB is not valid C# as-is. |
[seq] |
XAML activity sequence: For Each / Add Data Row / multiple Assigns; never one expression. |
[coded] |
Coded .cs workflow or Invoke Code only: statements, Dim, mutation loops. |
After more than ~2 chained [seq] steps or a real helper, stop hand-assembling XAML and write a coded workflow; see § When to move to coded.
Required imports & references
For a DataTable LINQ chain, set these in XAML TextExpression:
NamespacesForImplementation:System.Data,System.LinqReferencesForImplementation:System.Data,System.Data.Common,System.Data.DataSetExtensions
A scaffolded project (uip rpa init) already has all of these — untouched, the LINQ family just works. Add them only when hand-authoring a XAML file or after trimming imports. In coded .cs, add using System.Data; and using System.Linq; (coded/operations-guide.md § Using Statements Rules).
AsEnumerable / CopyToDataTable / DataRowComparer resolve through System.Data in modern Windows/cross-platform projects; legacy .NET Framework 4.6.1 requires System.Data.DataSetExtensions. Including that reference in both is safe. Without System.Linq, AsEnumerable fails at run (runtime JIT), not at uip rpa validate or even uip rpa build packaging.
VB ↔ C# translation key
Examples are VB, the default XAML expression language. Translate Function(r) r("Col") to r => r["Col"], () to [], and If(c,a,b) to c ? a : b; coded .cs and C#-expression XAML use C# forms.
Coded-only constructs that fail in VB XAML and inside CSharpValue because XAML binds expression trees: C# out parameters (int.TryParse(s, out int n); not a workflow/XAML OutArgument), ?., ?[], ??, collection initializers (new Dictionary<…>{ … }), and statement-body lambdas/IIFEs. Failures include CS8198 (out), CS8072 (?.), CS8074 (initializer), and CS0834 (statement-body lambdas/IIFEs). In C#-expression XAML only, optional-argument overloads also fail (CS0854).
XAML-safe alternatives:
- Parse: pre-declare
nand useIf(Integer.TryParse(s, n), n, 0); C#-expression XAML has noout-freeTryParse, so parse in a coded helper/workflow or accept the VB form—outcannot appear inCSharpValue. - Null-safe:
If(x Is Nothing, "", x.ToString())in VB, not?./??. - Build dictionaries across
Assigns /Invoke Method, not with an inline initializer.
See csharp-activity-binding-guide.md.
Choose the approach
| Task | Use | Notes |
|---|---|---|
| Simple single-condition filter | Filter Data Table activity | GUI, no expression. |
| Expression filter without new columns | dt_Data.Select("[Amount] > 1000") |
Returns DataRow(); string matching is case-INSENSITIVE by default and SQL-like. |
| Filter/sort/group/join/project | LINQ in one Assign |
Most flexible; ~2× faster than Join Data Tables on large sets. |
| Heavy multi-step transforms, unit-tested logic, safe accessors | coded .cs |
C# LINQ inline; see § When to move to coded. |
| Multi-step transform in C#-expression XAML | Coded Source File helper, Invoke Code, or coded workflow via Invoke Workflow File |
Expression trees forbid statements, out var, and optional-argument overloads (CS0854). |
| Key-value config/counters | Dictionary(Of K,V) |
|
| Tabular data | DataTable |
Typed columns; LINQ via .AsEnumerable(). |
When to move to coded
In VB projects, default to native Assign expressions for LINQ and JSON, not Invoke Code: Invoke Code introduces separately resolved assembly/import/version pitfalls, can drift from project references, and is not checked by validate; native expressions reuse project imports and round-trip in the designer. The [expr] snippets here are native.
When a transform exceeds expressions—more than 2 statement steps, a reusable safe accessor/helper, row mutation in a loop, real try/catch around parsing, or an unreadable one-liner—move to a coded .cs workflow (coded/operations-guide.md), still not Invoke Code. Coded workflows provide ?., out var, multi-statement logic, and unit tests.
Exception: C#-expression XAML workflows — the transform leaves the expression
C# XAML expressions are expression trees: no statements, out var (TryParse), or optional-argument overloads (CS0854) (xaml/common-pitfalls.md § C# XAML Expressions Compile as Expression Trees). Escalate to:
- Coded Source File helper: a
public staticmethod on a plain.csclass; call it from the expression (for example,NameRules.LastWord(name)). Import its namespace and reference the project's coded assembly (xaml/common-pitfalls.md § Coded Source File Types in XAML Expressions Need a Namespace Import and Assembly Reference). Invoke Code: keep logic inline, pass data through its Arguments collection, and authorCodeas an XML attribute (xaml/common-pitfalls.md § InvokeCode Code Property).- Coded Workflow via
Invoke Workflow File: move logic to a.csfile with[Workflow]+Execute; use when it needs coded services or activities.
Code vs activity chains for row processing: unless the user states a preference, complex bulk row processing (per-row parse + validate + branch + accumulate) goes to code — one of the escalations above — not an activity chain. Nested If/Switch levels inside a ForEach become unreadable, trip the analyzer nesting threshold, and every embedded expression re-fights the expression-tree limits. A simple ForEach row with ONE If or Switch is fine as plain XAML activities — more readable than code for that size.
A bare Coded Source File helper has no entry point and is called from expressions, XAML, or coded code. A Coded Workflow has [Workflow] + Execute and is invoked as a step via Invoke Workflow File (XAML) or RunWorkflow / typed workflows (coded); see coded/operations-guide.md.
For tabular Excel source/sink, use modern Use Excel File, not classic Excel Application Scope; route to Excel activity docs.
Safe data access first
Excel, scraping, UI, and queue data may contain DBNull, blanks, localized numbers, and bad dates. DBNull .ToString() returns "", so bare reads silently propagate blanks and CDbl/Convert.ToDateTime/ParseExact then throw; genuine Nothing causes an object-reference error. Direct-cast only typed, known-non-null columns; safely read String/Excel/scraped columns.
Inline safe reads [expr]:
' string cell (never throws)
If(IsDBNull(r("Name")), "", r("Name").ToString().Trim())
' number cell -> Decimal, invariant, default 0 on bad/blank/null (n is a Decimal out-var)
If(Decimal.TryParse(If(IsDBNull(r("Amount")), "", r("Amount").ToString()), Globalization.NumberStyles.Any, Globalization.CultureInfo.InvariantCulture, n), n, 0D)
Reusable [coded] accessor (plain Coded Source File, no CodedWorkflow base):
public static class Row
{
public static string Str(DataRow r, string c) => r.IsNull(c) ? "" : r[c].ToString().Trim();
public static decimal Dec(DataRow r, string c) => decimal.TryParse(Str(r, c), NumberStyles.Any, CultureInfo.InvariantCulture, out var d) ? d : 0m;
public static DateTime? Date(DataRow r, string c, string fmt) => DateTime.TryParseExact(Str(r, c), fmt, CultureInfo.InvariantCulture, DateTimeStyles.None, out var dt) ? dt : (DateTime?)null;
}
When invalid business data must stop the item, throw BusinessRuleException, not a crash: If String.IsNullOrWhiteSpace(Row.Str(r,"Id")) Then Throw New BusinessRuleException("Missing Id at row " & i).
DataTable transforms (LINQ)
Call .AsEnumerable() first and .CopyToDataTable() to produce a DataTable. The casts below assume typed/clean columns; safely wrap String/Excel fields as above.
MANDATORY: guard every possibly empty CopyToDataTable() result. Otherwise it throws InvalidOperationException: "The source contains no DataRows":
[If(q.Any(), q.CopyToDataTable(), dt_Data.Clone())]
dt_Data.Clone() is an empty same-schema table; dt_Data.Copy() includes schema and all rows.
Filter, sort, dedup, paginate — each [expr]
dt_Data.AsEnumerable().Where(Function(r) r("Status").ToString().Trim().Equals("active", StringComparison.OrdinalIgnoreCase))
dt_Data.AsEnumerable().OrderByDescending(Function(r) CDbl(r("Amount"))).CopyToDataTable()
dt_Data.AsEnumerable().Distinct(DataRowComparer.Default).CopyToDataTable()
dt_Data.AsEnumerable().GroupBy(Function(r) r("Id").ToString()).Select(Function(g) g.First()).CopyToDataTable()
dt_Data.AsEnumerable().Skip(10).Take(10).CopyToDataTable()
Guard each CopyToDataTable() when no match is possible. dt_Data.Select/Filter Data Table matching is case-INSENSITIVE by default; use StringComparison.Ordinal for case-sensitive matching. C# equivalents use r => r["Status"]… and g => g.First().
Aggregate — each [expr]
dt_Data.AsEnumerable().Sum(Function(r) CDbl(r("Amount")))
dt_Data.AsEnumerable().Count(Function(r) r("Status").ToString().Trim().Equals("active", StringComparison.OrdinalIgnoreCase))
dt_Data.AsEnumerable().Any(Function(r) CDbl(r("Amount")) > 10000)
Compare two DataTables (diff) — each [expr]
dt_A.AsEnumerable().Except(dt_B.AsEnumerable(), DataRowComparer.Default)
dt_A.AsEnumerable().Where(Function(a) Not dt_B.AsEnumerable().Any(Function(b) b("Id").ToString() = a("Id").ToString()))
The first returns rows in A not in B by whole row; guard and copy it when producing a DataTable. The second returns A rows whose key is absent from B.
Join two DataTables (VLOOKUP equivalent) — [expr]
| Need | Use |
|---|---|
| One value from lookup | Lookup Data Table activity |
| Simple combination | Join Data Tables activity, slower at scale |
| Combine/filter/shape in one pass | LINQ join |
(From a In dt_A.AsEnumerable()
Join b In dt_B.AsEnumerable() On a("Id").ToString() Equals b("Id").ToString()
Select New Object(){ a("Id"), a("Name"), b("Region") }).ToList()
Select New Object(){…} produces List(Of Object()); type the receiving variable accordingly, or project to an anonymous type for named fields.
Remove blank rows — [expr]
Remove trailing all-empty Excel/scraping rows because they pollute counts/output and break numeric/date casts:
dt_Data.AsEnumerable().Where(Function(r) Not r.ItemArray.All(Function(f) f Is DBNull.Value OrElse String.IsNullOrWhiteSpace(f.ToString())))
Guard and CopyToDataTable() the result.
Group-by-sum into a NEW DataTable — [seq] (or [coded])
This is not an Assign: use For Each over groups and Add Data Row. dt_Grouped must already contain Category(String) and Total(Decimal) columns.
For Each g In dt_Data.AsEnumerable().GroupBy(Function(r) r("Category").ToString())
dt_Grouped.Rows.Add(g.Key, g.Sum(Function(r) CDec(r("Amount"))))
Next
In XAML, use ui:ForEach with <ui:ForEach.Body> over …GroupBy(...).Select(Function(g) New Object(){g.Key, g.Sum(...)}).ToList(), with Add Data Row into dt_Grouped.
Convert DataTable ↔ collections / JSON — [expr]
dt_Data.Columns.Cast(Of DataColumn)().ToDictionary(Function(c) c.ColumnName, Function(c) dt_Data.Rows(0)(c.ColumnName).ToString())
Newtonsoft.Json.JsonConvert.SerializeObject(dt_Data)
Newtonsoft.Json.JsonConvert.DeserializeObject(Of System.Data.DataTable)(jsonString)
CollectionToDataTable builds a DataTable from List(Of T).
Iterating rows & common errors
- Use For Each Row in Data Table for row work;
CurrentRowis aDataRow. It does not support persistence; inside a Long Running Workflow use coded code (xaml/long-running-workflow-guide.md). - MANDATORY modify-during-iteration rule: never add/remove rows from the table being iterated; it throws
Collection was modified; enumeration operation may not execute. Iterate a fresh array (dt_Data.Select()), then callAcceptChanges()after[seq]/[coded]:
For Each r In dt_Data.Select()
If r("Status").ToString() = "drop" Then r.Delete()
Next
dt_Data.AcceptChanges()
- A null cell is
DBNull.Value, notNothing; use § Safe data access first. - Add Data Row error
Input array is longer than the number of columns in this table: a wider sourceItemArraywas passed to a narrower target. Add missing target columns or build anObject()matching target count/order.
Strings & RegEx
Always Trim() text from UI/web/Excel; check String.IsNullOrWhiteSpace(s) before use. In loops use System.Text.StringBuilder (sb.AppendLine(...), then sb.ToString()), not &. Split multiple delimiters with s.Split(New Char(){";"c, ","c}); format numbers with value.ToString("N2", Globalization.CultureInfo.InvariantCulture) because bare ToString("N2") follows machine locale.
Use System.Text.RegularExpressions.Regex without a package; each is [expr]:
System.Text.RegularExpressions.Regex.IsMatch(input, "\d{3}-\d{2}-\d{4}")
System.Text.RegularExpressions.Regex.Match(input, "INV-\d+").Value
System.Text.RegularExpressions.Regex.Matches(input, "\$[\d,]+\.?\d{0,2}")
System.Text.RegularExpressions.Regex.Replace(input, "\s+", " ")
| Pattern | RegEx |
|---|---|
[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,} |
|
| Phone (US) | \(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4} |
Date MM/DD/YYYY |
\d{2}/\d{2}/\d{4} |
| Currency (USD) | \$[\d,]+\.?\d{0,2} |
| Invoice | INV-\d{4,10} |
| ZIP (US) | \d{5}(-\d{4})? |
| Decimal | -?\d+\.?\d* |
Patterns are unanchored and extract anywhere. For full-string validation, anchor with ^…$, such as ^\d{5}(-\d{4})?$ for ZIP.
Pattern-string escaping:
- VB (XAML
Assignor coded VB):"\d+". - C# coded:
@"\d+"or"\\d+"; bare"\d+"is a compile error. - Any XAML attribute: raw
<and>are illegal XML; use</>. Thus named-group XAML uses(?<amt>…); raw(?<amt>…)is only for coded.cs.
Named-group examples:
System.Text.RegularExpressions.Regex.Match(input, "(?<amt>\$[\d,.]+)").Groups("amt").Value
Regex.Match(input, @"(?<amt>\$[\d,.]+)").Groups["amt"].Value
Prefer named groups; escape literal dots. For untrusted/long input, set a timeout to prevent catastrophic backtracking: New Regex(pattern, RegexOptions.None, TimeSpan.FromSeconds(5)). Matches does not support persistence; use code in a Long Running Workflow.
DateTime & type conversion
Use an explicit format and invariant culture. MM is month and mm is minutes; "mm/dd/yyyy" silently misparses June as January, so only a test catches it.
DateTime.ParseExact(dateText, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture)
DateTime.ParseExact(s, New String(){"dd/MM/yyyy", "dd.MM.yyyy"}, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None)
For external dates use TryParseExact, as in § Safe data access first.
| Method | Bad input | Use |
|---|---|---|
CInt(v) / Integer.Parse(v) |
throws | Known-good data |
Convert.ToInt32(v) |
throws; Nothing → 0 |
Known-good; literal Nothing needs CObj(Nothing) in VB XAML because of overload ambiguity |
Integer.TryParse(v, n) / Decimal.TryParse / DateTime.TryParseExact |
returns False, out = default |
External/user/Excel input; default choice |
Read a TryParse result in the same composite expression: If(Integer.TryParse(v, n), n, 0), with n pre-declared. A standalone Integer.TryParse(v, n) does not reliably write n for a later step because WF may bind ByRef to a copy. The same applies to Dictionary.TryGetValue.
Specify culture for external numbers/dates: Double.Parse("1,234.56", System.Globalization.CultureInfo.InvariantCulture); bare CDbl follows machine locale. CInt("12.5") rounds banker's-style to even, not truncates; use CInt(Math.Floor(...)) to truncate. CBool("yes") throws; only "True"/"False" are accepted. GenericValue string comparison is lexical, not numeric; cast first.
Collections
[expr] initialization and reads:
New List(Of String) From {"a", "b"}
New Dictionary(Of String, Integer) From {{"a", 1}, {"b", 2}}
myDict.ContainsKey("k")
If(myDict.TryGetValue("k", value), value, 0)
value is a pre-declared out variable. Iterate/mutate under [seq]/[coded]:
For Each kvp As KeyValuePair(Of String, Object) In myDict
' kvp.Key, kvp.Value
Next
For Each kvp In dict2 : dict1(kvp.Key) = kvp.Value : Next
The merge gives precedence to dict2. Nested config [expr]: DirectCast(configDict("DatabaseSettings"), Dictionary(Of String, String))("ConnectionString").
C# coded permits collection initializers ({ ["a"]=1 }), null-conditional (dict.GetValueOrDefault("k")?.Trim()), and null-coalescing (?? "").
JSON (JObject / JArray)
Newtonsoft.Json ships with UiPath projects; use Newtonsoft.Json.Linq. Deserialize JSON / Deserialize JSON Array wrap it. System.Text.Json is the modern BCL alternative in coded code.
[expr] parse/read:
Newtonsoft.Json.Linq.JObject.Parse(jsonString)
Newtonsoft.Json.Linq.JArray.Parse(jsonArrayString)
jObj("name").ToString()
jObj("address")("city").ToString()
jArr(0)("name").ToString()
jObj("count").Value(Of Integer)()
If(jObj("optional") IsNot Nothing AndAlso jObj("optional")("nested") IsNot Nothing, jObj("optional")("nested").ToString(), Nothing)
jArr.Where(Function(i) i("status").ToString() = "active")
jArr.Select(Function(i) i("name").ToString()).ToList()
VB ?. does not compile in a XAML Assign (BC37240); use the guard shown. Build/modify under [coded]/[seq], not one Assign:
Dim o = New Newtonsoft.Json.Linq.JObject()
o("name") = "John" : o("age") = 30
o.ToString()
For an API response, parse responseBody; if response("error") IsNot Nothing, throw BusinessRuleException(...); then read DirectCast(response("data")("items"), Newtonsoft.Json.Linq.JArray).
Coded (.cs) note
Coded workflows use C# directly: r => r["Col"], ternary, out, ?., ??, collection initializers, verbatim @"\d+" regex, and query or method LINQ. Add usings System.Data, System.Linq, System.Text.RegularExpressions, and System.Globalization per coded/operations-guide.md § Using Statements Rules. The XAML C# binding wrapper is separate: xaml/csharp-activity-binding-guide.md.
Open this reference as its own page
Debugging Workflows with the debug group
The uip rpa debug group (plus uip rpa run and uip rpa execution cancel) provides full interactive debugging for both XAML workflows and coded (.cs) files. Beyond simple execution (run), it supports breakpoints, step-by-step execution, exception handling, isolated activity testing, and runtime state inspection — all from the CLI.
This is a powerful complement to validate (static validation). While validate catches structural and type issues at design time, the debugger catches runtime problems: wrong API responses, null references, logic errors, failed deserialization, and more. Use both together for comprehensive workflow validation.
Studio Desktop vs headless
Most debugging works on headless Studio with no Studio Desktop install: run, debug start (including activity-targeted breakpoints via --breakpoints), all stepping verbs (debug step-over, debug step-into, debug step-out), debug continue, debug break, debug resume, debug continue-retry, debug continue-ignore, debug state, debug set-breakpoints, execution cancel, debug restart-from-top.
On the headless backend, every debug command returns at the next stable state — paused at an activity, suspended on an exception, or completed — carrying DebugState / DebugDetails in the result, so you always learn where execution stands from the command's own response. See The stable-state debug loop.
Studio Desktop is required for any flow that targets the focused activity, because focusing goes through uip rpa focus-activity and only Studio Desktop has a designer to focus:
| Command | Why it needs Studio Desktop |
|---|---|
debug test-activity |
Operates on the focused activity — requires focus-activity first. Headless rejects the command |
debug start-from-here |
Operates on the focused activity — requires focus-activity first. Headless rejects the command |
debug toggle-breakpoint |
Toggles on the focused activity/line — requires focus-activity first. Headless rejects the command; set headless breakpoints with --breakpoints on debug start (or debug set-breakpoints mid-session), which target activities by IdRef with no focusing step |
focus-activityon headless is a silent no-op — it returnssuccess: truebut focuses nothing (there is no designer). Do NOT use it to "target" an activity for a headless debug flow and do not treat its success as confirmation: on headless, the focus-dependent verbs above fail withUnknown commandregardless, and activity targeting goes through--breakpointsinstead.
Before invoking any of the above, run uip rpa studio start --project-dir "<PROJECT_DIR>" --output json and ensure the project is open in Studio Desktop. See environment-setup.md § Edge case: requiring Studio Desktop.
Command Reference
run and debug start take a file path and optional inputs:
uip rpa run --file-path <relative-path> [--input-arguments key=value]... [--log-level <level>] [--skip-build] [--output json]
uip rpa debug start --file-path <relative-path> [--input-arguments key=value]... [--breakpoints item]... [--log-level <level>] [--skip-build] [--output json]
debug test-activity and debug start-from-here operate on the currently focused activity (no --file-path):
uip rpa debug test-activity [--input-arguments key=value]... [--input-variables key=value]... [--log-level <level>] [--output json]
uip rpa debug start-from-here [--input-arguments key=value]... [--input-variables key=value]... [--log-level <level>] [--output json]
The mid-session verbs (break, continue, resume, continue-retry, continue-ignore, step-into, step-over, step-out, state) operate on the active debug session and take only the optional --wait-timeout-seconds. debug set-breakpoints takes --breakpoints. debug toggle-breakpoint and debug restart-from-top take no parameters.
| Parameter | Description |
|---|---|
--file-path |
Workflow file to run (relative to project root). Applies to run and debug start only |
--input-arguments |
Project-level input arguments as repeatable key=value pairs (= string, := raw JSON; see cli-reference.md § Passing structured inputs). Only for run, debug start, debug test-activity, and debug start-from-here (see Input Variables vs Input Arguments) |
--input-variables |
Workflow-level variable values as repeatable key=value pairs (values are VB/C# expressions — always =). Only for debug test-activity and debug start-from-here (see Input Variables vs Input Arguments) |
--breakpoints |
Activity breakpoints for XAML debugging (headless backend). One array item per flag occurrence, comma-separated key=value inside an item: --breakpoints 'workflowFile=Main.xaml,activityIdRef=Assign_1'. Keys: workflowFile (required; workflow path relative to the project root), activityIdRef (the target activity's sap2010:WorkflowViewState.IdRef attribute value from the XAML — the stable way to address an activity you can read straight from the file), optional condition (VB/C# expression; breaks only when it evaluates to True), hitCount:=N (break only on exactly the Nth hit), enabled (defaults to true). Whole payload from a file: --breakpoints-file breakpoints.json. Used by debug start (initial set) and debug set-breakpoints (replaces the running session's whole set) |
--wait-timeout-seconds |
Maximum seconds a mid-session verb waits for the next stable state before returning DebugState: "Running" instead of hanging. Default 120 (0 for debug state, making it an instant probe). Headless backend only |
--log-level |
Minimum log level: Verbose, Trace (default), Information, Warning, Error, Critical |
--skip-build |
Skip the pre-run build step (use only when you've just built) |
--output |
Output format: json (recommended), table, yaml, plain |
--profiling |
Collect per-activity timings and runtime screenshots — verifies UI automation correctness and workflow performance. Only effective on start verbs (run, debug start, debug test-activity, debug start-from-here); ignored on stepping / breakpoint verbs. Boolean flag (no value needed). See Profiling Workflow Performance. |
Debug Verbs
| Verb | When to Use | What It Does |
|---|---|---|
run |
Run without debugging | Executes the workflow to completion. The default authoring loop verb |
debug start |
Begin a debug session | Starts execution in debug mode and returns at the first stable state: Paused at a breakpoint (pass --breakpoints to set them), Suspended on an exception, or Completed if nothing interrupts the run. The response's DebugState / DebugDetails say where execution stands; the session stays alive for the mid-session verbs |
debug test-activity |
Test one activity in isolation | Isolates the currently focused activity and executes it in a temporary test workflow. Requires focus-activity first → Studio Desktop required (see Studio Desktop vs headless). Use --input-variables to set variable values and --input-arguments to set argument values |
debug start-from-here |
Debug from a specific activity | Starts a debugging session from the currently focused activity, skipping all preceding activities. Requires focus-activity first → Studio Desktop required (see Studio Desktop vs headless). Use --input-variables to set variable values and --input-arguments to set argument values |
debug toggle-breakpoint |
Set/remove breakpoints interactively (Studio Desktop only) | Toggles a breakpoint on the currently focused activity (XAML) or line (.cs). Use uip rpa focus-activity to focus beforehand. For XAML, cycles through 3 states: enabled → disabled → no breakpoint. For .cs, cycles through 2 states: breakpoint → no breakpoint. Not available headless (rejected as an unknown command) — use --breakpoints on debug start or debug set-breakpoints instead |
debug step-over |
Execute one activity and pause | Executes the current activity, then pauses at the next sibling activity. Does not enter child scopes (e.g., stays at the For Each level, doesn't step into its body). Returns the new paused state with locals |
debug step-into |
Drill into child activities | Executes and pauses at the first child activity inside the current scope. Use to enter loops, sequences, Try-Catch blocks, etc. Returns the new paused state with locals |
debug step-out |
Exit the current scope | Continues execution until the current scope completes, then pauses at the parent level. Use to leave a loop body or nested sequence. Returns the new paused state with locals |
debug continue |
Run to next breakpoint | Resumes execution and returns at the next stable state — the next breakpoint (Paused), an exception (Suspended), or the end of the run (Completed) |
debug break |
Pause execution | Pauses a running debug session at the next executed activity and returns the paused state with locals |
debug state |
Inspect without side effects | Reports the session's current DebugState (Running, Paused, Suspended, Completed, or None when no session is active) plus the last captured details. Instant by default; pass --wait-timeout-seconds to long-poll a running session for its next stable state |
debug set-breakpoints |
Change breakpoints mid-session | Replaces the active session's whole breakpoint set with the --breakpoints payload. For a new session, pass --breakpoints on debug start instead |
debug resume |
Resume from suspended state | Resumes execution when the workflow is in a suspended (not just paused) state |
debug continue-retry |
Retry after exception | Resumes execution and retries the current activity that caused the exception. Use when you've fixed the underlying issue (e.g., network timeout) and want to try again |
debug continue-ignore |
Skip past exception | Resumes execution and ignores the exception on the current activity, pausing at the next activity. Use when the error is non-critical and you want to proceed |
execution cancel |
End the session | Cancels the currently active execution — works for both run and debug start |
debug restart-from-top |
Start over | Restarts execution from the beginning of the workflow without ending the debug session. Breakpoints are preserved |
The stable-state debug loop (headless)
On the headless backend, debugging is a synchronous request/response loop: every command returns when execution reaches the next stable state, and the response tells you exactly where things stand. No command hangs waiting for a human — if nothing stable is reached within --wait-timeout-seconds, the response says Running and how to proceed.
DebugState values in the response:
DebugState |
Meaning | What to do next |
|---|---|---|
Paused |
Stopped at a breakpoint or after a step/break. DebugDetails carries the current activity (name, id, workflow file) and a snapshot of in-scope variables, arguments, and properties |
Inspect DebugDetails, then step-over / step-into / step-out / continue, or execution cancel |
Suspended |
Stopped on an exception; the session is still alive. A suspension does not mean the workflow leaves the exception unhandled: the debugger hooks every activity its parent schedules without a fault handler (each child of a Sequence or an If, the root of an invoked workflow; not the activity placed directly in a Try Catch's Try) and suspends when a fault leaves a hooked activity, even when a Try Catch or Retry Scope above will handle it — once per hooked level the fault climbs, and at each failed Retry Scope attempt. errorMessage calls the exception unhandled every time. DebugDetails carries the exception type, message, the activity the fault is leaving, and locals |
Look in the workflow for a Try Catch with a Catch for the exception's type or a base type, or a Retry Scope, around that activity. If one handles it, continue until the run reaches it: a fault the workflow tolerates (an optional element that is absent) is continued, not repaired. Otherwise continue propagates the exception and the run fails, continue-retry re-runs the faulted activity, continue-ignore skips it, and execution cancel ends the session |
Completed |
The run finished. The response is the normal run result (§ Output Format) | Read the run result; the session is gone |
Running |
The wait timed out before a stable state was reached — execution is still going | Poll with debug state, send debug break to pause at the next activity, or execution cancel |
None |
No debug session is active | Start one with debug start |
The canonical loop:
# Start with breakpoints on the activities you care about — returns Paused at the first hit
uip rpa debug start --file-path Main.xaml \
--breakpoints 'workflowFile=Main.xaml,activityIdRef=Assign_1' --output json
# Inspect DebugDetails (activity + locals), then advance — each call returns the next state
uip rpa debug step-over --output json
uip rpa debug continue --output json
# If a response says Suspended, decide on the exception:
uip rpa debug continue-ignore --output json # or continue-retry / continue / execution cancel
# Not sure what's happening? Probe without side effects:
uip rpa debug state --output json
Breakpoints are addressed by activityIdRef — the sap2010:WorkflowViewState.IdRef attribute you can read directly from the XAML you authored — so no focus-activity (and no Studio Desktop) is needed. Conditional breakpoints (condition) and hit counts (hitCount:=N) are evaluated by the runtime.
Input Variables vs Input Arguments
These serve different purposes and apply to different scopes:
Arguments (
--input-arguments) are project-level In/Out/InOut parameters defined in the project's argument list. They are the workflow's public interface — how callers pass data in and receive data back. Applicable forrun,debug start,debug test-activity, anddebug start-from-here.Variables (
--input-variables) are workflow-level local state declared inside the workflow and scoped to specific activities or containers (e.g., a Sequence, a For Each body). They are internal to the workflow and not visible from outside. Only applicable fordebug test-activityanddebug start-from-here— these verbs execute from a specific activity's context, so you can pre-set the variables that activity reads from.
--input-arguments |
--input-variables |
|
|---|---|---|
| What they are | Project-level parameters (In/Out/InOut) | Workflow-internal variables scoped to activities |
| Where defined | Project argument list (visible in Studio's Arguments panel) | Inside the workflow (visible in Studio's Variables panel) |
| Applicable verbs | run, debug start, debug test-activity, debug start-from-here |
debug test-activity, debug start-from-here only |
Value format (run / debug start) |
key=value pairs (= string, := raw JSON): name=John, age:=30 |
N/A |
Value format (debug test-activity / debug start-from-here) |
VB.NET or C# expressions — always = |
VB.NET or C# expressions — always = |
Expression Value Examples
For debug test-activity and debug start-from-here, both --input-arguments and --input-variables values must be VB.NET or C# expressions matching the project language. Always use = pairs (the expression is a string — := would corrupt it), one variable per flag occurrence. Expressions containing double quotes (string literals) cannot be passed inline on Windows PowerShell 5.1 — write them to a UTF-8 file and use key=@file.
VB.NET projects:
# Integer variable — the expression 42
--input-variables count=42
# Boolean variable (VB uses True/False, capitalized)
--input-variables isActive=True
# Null / unset (VB keyword)
--input-variables result=Nothing
# New object — single-quote tokens containing spaces
--input-variables 'config=New Dictionary(Of String, Object)'
# String variable — the expression needs quotes, so pass it from a file.
# PowerShell: Set-Content -Encoding UTF8 greeting.txt '"Hello World"'
# bash: printf '"Hello World"' > greeting.txt
--input-variables greeting=@greeting.txt
# Multiple variables at once — repeat the flag
--input-variables name=@name-expr.txt --input-variables age=30 --input-variables isActive=True
C# projects:
# Boolean variable (C# uses true/false, lowercase)
--input-variables isActive=true
# Null / unset (C# keyword)
--input-variables result=null
# New object — single-quote tokens containing spaces
--input-variables 'config=new Dictionary<string, object>()'
# String variable — quoted literal goes through a file
--input-variables greeting=@greeting.txt
Important: values are committed as expression text.
count=42yields the expression42(an integer literal). To pass the string"200", the expression must contain the quotes —"200"— which survives only via the file form:temperature=@expr.txtwith the file containing"200". Whole payloads can also be loaded from a JSON file:--input-variables '@vars.json'(single-quote the@token in PowerShell) or--input-variables-file vars.json.
Output Format
run and debug start both return {Result, Code, Data}. Data's shape is set by the backend that ran the workflow — Headless Studio (Helm) when no Studio Desktop instance has the project open, Studio Desktop when one does (cli-reference.md § Headless Studio (Helm) vs Studio Desktop). Identify the shape by the keys present.
Helm shape
A clean run, then the same workflow under debug start:
[Information] Starting execution...
[Information] <PROJECT_NAME> execution started
[Information] Sum: 10
[Information] <PROJECT_NAME> execution ended in: 00:00:00
{ "Result": "Success", "Code": "Run",
"Data": { "output": "{}", "hasErrors": false, "errorMessage": null, "profiling": null, "debugState": null, "debugDetails": null, "errorScope": null } }
{ "Result": "Success", "Code": "DebugStart",
"Data": { "output": "{}", "hasErrors": false, "errorMessage": null, "profiling": null, "debugState": "Completed", "debugDetails": null, "errorScope": null } }
| Field | Type | Meaning |
|---|---|---|
output |
string |
Workflow's serialized output arguments JSON once the run ends — {"out_Sum":10} for an entry point with out_Sum, "{}" for one that declares none, also on a run that faulted inside an activity. "" while a session is Paused, Suspended or Running, on debug state, and when the run never started (validation failure, missing entry point). Carries the workflow's data, not a verdict. |
hasErrors |
bool |
true when the run ended without succeeding: an unhandled exception that ended a run, a compile/validation failure, a missing entry point. false otherwise — including while Suspended on an exception, because the session is still alive and the outcome undecided. |
errorMessage |
string? |
The failure text when hasErrors: true: an activity fault gives Source: <activity>, Message: …, Exception Type: … and the stack; a compile/validation failure gives Validation failed with N error(s): and the diagnostics; a missing entry point gives Message: The <file> workflow cannot be found …. On the response that reports a Suspended session it carries guidance (which commands apply) with hasErrors: false. null otherwise. |
debugState |
string? |
Debug sessions only (null on plain run): Paused (breakpoint), Suspended (exception), Running (debug state polled mid-run), Completed, or None (debug state with no session). See The stable-state debug loop. |
debugDetails |
string? |
Debug sessions only: JSON snapshot for the state — Activity, ActivityId, WorkflowFile, CurrentActivity and locals when Paused; ExceptionType, Message, Activity, CurrentActivity and locals when Suspended; "" while Running; null otherwise. |
profiling |
object? |
null unless --profiling was passed on a start command; then {"outputDirectory": "<absolute path>"} — the run's *.uistat and screenshot folder (verifies UI automation correctness and workflow performance). See Profiling Workflow Performance. |
errorScope |
string? |
Set only when the pre-run validation failed, and names whose errors they are: "target" — the file passed to --file-path; "dependency" — a workflow that file invokes; "project" — the run could not be narrowed to the file and the workflows it invokes, so the whole project was validated and the errors may sit in files the run never reaches. null otherwise. |
On Helm the workflow's log output is not in the envelope. Log Message activities and system traces stream to stdout as [Level] message lines above the JSON envelope, live, while the run executes. That is where a logged value is read back to confirm runtime behavior — do not strip those lines. In a debug session only the debug start call streams them: a line logged after it returns (after a continue or a step) reaches no later command's output, so read it from the Robot's execution log (%LOCALAPPDATA%\UiPath\Logs\<yyyy-MM-dd>_Execution.log on Windows), where each line ends in a JSON object with message and the workflow's fileName. Output arguments are read from output, from the workflow's own log lines, or from artifacts the workflow wrote.
The outer
Resultreports the CLI invocation, NOT the workflow. On Helm it isValidationErrorfor an unknown flag or a filter that failed to evaluate;Failurefor arunordebug continuewhose workflow faulted, failed validation, or named a missing entry point (Messageholds theDatafields JSON-encoded,hasErrors: true) and for a project directory that cannot be opened or an executor that is still busy (Messageholds{"success": false, "errorMessage": "…"}); andSuccessfor everydebug startthat reached the runtime — including one suspended on an exception. Never treatResult: "Success"as a passing run.Helm verdict: a run passed only when
Data.hasErrorsisfalseANDData.errorMessageisnullANDData.debugStateisnullor"Completed". All three are required: a suspended debug session reportshasErrors: falsewithdebugState: "Suspended"and guidance inerrorMessage; a completed failure reportshasErrors: truewith the chain inerrorMessage.A test case's verification that fails with
ContinueOnFailureTrue(the default) leaves all three clean. Its own[Error]line, the verification's result message, is the only sign: check a test case's verification lines in addition to the verdict.Do NOT use a log line's level as a failure signal — workflow
Log Messageactivities emit at any level, and a clean run that logs atErrorstill returnshasErrors: false. Treating log levels as a verdict flips green runs to "failed". Conversely, when a run has failed,errorMessageand the[Error]lines above the envelope carry the most specific diagnosis — read them for the root cause after the verdict is already established.
Helm examples:
// Successful completed run — workflow logged a warning, but hasErrors is false
{ "output": "{\"resultCode\":\"OK\"}", "hasErrors": false, "errorMessage": null, "debugState": "Completed", "debugDetails": null }
// Failed completed run — compile or runtime failure ended the session
{ "output": "", "hasErrors": true, "errorMessage": "Source: HttpRequest_1\nMessage: ...", "debugState": "Completed", "debugDetails": null }
// Paused at a breakpoint — current activity + locals in debugDetails
{ "output": "", "hasErrors": false, "errorMessage": null, "debugState": "Paused",
"debugDetails": "{\"Activity\":\"Assign x\",\"ActivityId\":\"1.5\",\"WorkflowFile\":\"...\\Main.xaml\",\"Locals\":{...}}" }
// Suspended on an exception — session alive, hasErrors still false, errorMessage carries guidance
{ "output": "", "hasErrors": false,
"errorMessage": "Execution suspended on an unhandled exception; the session is still alive. Send Continue..., ContinueRetry..., ContinueIgnore..., or Stop...",
"debugState": "Suspended",
"debugDetails": "{\"ExceptionType\":\"System.InvalidOperationException\",\"Message\":\"...\",\"Activity\":\"Throw\",\"Locals\":{...}}" }
Studio Desktop shape
The same clean run (or debug start, whose Code is DebugStart) with the project open in Studio Desktop:
{ "Result": "Success", "Code": "Run",
"Data": { "output": "Session ended", "errors": [],
"logEntries": [ { "source": "Compile", "level": "Information", "message": "Restoring nuget packages" },
{ "source": "Debug", "level": "Information", "message": "<PROJECT_NAME> execution started" },
{ "source": "Debug", "level": "Trace", "message": "Unregistered service requested: UiPath.UIAutomationNext.Contracts.IStudioService)" },
{ "source": "Debug", "level": "Information", "message": "Sum: 10" },
{ "source": "Debug", "level": "Information", "message": "<PROJECT_NAME> execution ended in: 00:00:06" } ],
"debugState": "Completed" } }
| Field | Type | Meaning |
|---|---|---|
output |
string |
Status string: "Session ended" when the run completed; "Failed to open the file <absolute path>" when the entry point does not exist. Not the output arguments. |
errors |
array |
Empty on a passing run and on a missing entry point. |
logEntries |
array |
{source, level, message} per entry, source = Compile (restore/build phase) or Debug (execution). The workflow's Log Message output lands here, among Trace-level runtime entries (Unregistered service requested …, Audit: …). Nothing streams above the envelope. Empty when the file could not be opened. |
debugState |
string |
"Completed" on a completed run or debug start. Absent when the file could not be opened. |
Studio Desktop verdict: a run passed only when
Data.errorsis empty ANDData.outputis"Session ended". Both are required: a missing entry point returns outerResult: "Success"witherrors: [],logEntries: []andoutput: "Failed to open the file <path>". An--input-argumentskey the workflow does not declare is accepted silently and the run completes. Log-entrylevelis not a failure signal here either.
Choosing the Right Verb
| Situation | Verb | Why |
|---|---|---|
| "Run the whole workflow and check the result" | run |
Full run, no debugging overhead |
| "This one activity isn't working — test it with specific inputs" | debug test-activity |
Isolates the activity, fastest feedback loop |
| "The bug is in activity X but I need the debug session to step through from there" | debug start-from-here |
Skips everything before X, gives full debug control from that point |
| "I need to step through the entire workflow from the start" | debug start |
Full debug session with breakpoints, stepping, variable inspection |
| "I want to verify the fix works at runtime after editing" | run or debug test-activity |
Quick validation — use debug test-activity if you only changed one activity |
Common Debugging Workflows
1. Quick Breakpoint Debug Session
The most common pattern: start debugging with breakpoints on the activities you suspect, inspect the state each pause returns, then step or continue. Runs fully headless — breakpoints are addressed by the activity's IdRef straight from the XAML, no focusing step.
# 1. Start debugging with a breakpoint — returns Paused at the breakpoint,
# with the current activity and locals in DebugDetails
uip rpa debug start --file-path "GetStockPrices.xaml" \
--breakpoints 'workflowFile=GetStockPrices.xaml,activityIdRef=Assign_1' \
--output json
# 2. Read DebugDetails: current activity + variables/arguments/properties snapshot.
# Then step through — each call returns the next paused state with fresh locals:
uip rpa debug step-over --output json
# 3. Or run to the next breakpoint / completion:
uip rpa debug continue --output json
# 4. When done, cancel the session (skip if the last response was already Completed)
uip rpa execution cancel --output json
Conditional breakpoints and hit counts work the same way:
--breakpoints 'workflowFile=Main.xaml,activityIdRef=Assign_1,condition=count > 3'
--breakpoints 'workflowFile=Main.xaml,activityIdRef=Click_2,hitCount:=3'
On Studio Desktop, the interactive alternative is
focus-activity+debug toggle-breakpoint(see Studio Desktop vs headless).
2. Test a Single Activity in Isolation
Use debug test-activity to run just the currently focused activity without executing the entire workflow. Useful for verifying an activity works with specific inputs.
Studio Desktop required —
focus-activityanddebug test-activityboth rely on it (headless rejectsdebug test-activity, andfocus-activitysilently no-ops). On a headless-only setup, fall back todebug start --breakpoints 'workflowFile=<file>,activityIdRef=<IdRef>'— pause right at the activity, inspect its inputs inDebugDetails, then step over it and check the result.
# 1. Focus the activity to test (Studio Desktop required)
uip rpa focus-activity --activity-id "DeserializeJson_1"
# 2. Run it in isolation, pre-setting any variables it reads from.
# temperature is a String — its expression needs quotes, so pass it from a file:
# PowerShell: Set-Content -Encoding UTF8 temp-expr.txt '"200"' bash: printf '"200"' > temp-expr.txt
uip rpa debug test-activity \
--input-variables temperature=@temp-expr.txt \
--output json
# 3. Check the output:
# - hasErrors / errorMessage → compile/validation issues, unhandled exceptions
# - Streamed log entries → runtime messages from the activity (observability, not a verdict)
# - Output → workflow's serialized output args on success
3. Debug From a Specific Activity
Use debug start-from-here to skip straight to the activity you care about, avoiding stepping through earlier activities.
Studio Desktop required —
focus-activityanddebug start-from-hereboth rely on it (headless rejectsdebug start-from-here, andfocus-activitysilently no-ops). On a headless-only setup, usedebug start --breakpoints 'workflowFile=<file>,activityIdRef=<IdRef>'— the run starts from the top, but pauses at the activity you care about with locals in hand.
# 1. Focus the activity to start from (Studio Desktop required)
uip rpa focus-activity --activity-id "HttpRequest_1"
# 2. Start debugging from that point, pre-setting variables.
# apiUrl is a String — its expression needs quotes, so pass it from a file:
# PowerShell: Set-Content -Encoding UTF8 api-url.txt '"https://api.example.com/weather"'
uip rpa debug start-from-here \
--input-variables apiUrl=@api-url.txt \
--output json
# 3. The debugger runs from the focused activity — step through or continue
uip rpa debug step-over --output json
# 4. Cancel when done
uip rpa execution cancel --output json
4. Exception Investigation
When a debug session stops on an exception, the command that was running returns DebugState: "Suspended" — the session is alive and waiting for your decision. Which exceptions suspend and what DebugDetails carries: The stable-state debug loop.
# Start debugging — if an exception fires, the response comes back Suspended
uip rpa debug start --file-path "MyWorkflow.xaml" --output json
# Inspect the Suspended response:
# - debugDetails → exception type + message + faulting activity + locals at the fault
# - hasErrors stays false — the outcome is not decided yet
# - errorMessage carries the guidance on which commands apply
# Then choose how to proceed:
# Option A: Retry the failed activity (e.g., transient network error)
uip rpa debug continue-retry --output json
# Option B: Ignore the exception and continue past it (pauses at the next activity)
uip rpa debug continue-ignore --output json
# Option C: Propagate the exception (to the next suspension or the handler that catches it; with none, the run fails — envelope in § Output Format)
uip rpa debug continue --output json
# Option D: Cancel and fix the root cause
uip rpa execution cancel --output json
5. Runtime Validation After Edits
Use debugging to verify that a fix actually works at runtime, beyond what validate (static validation) can check.
# 1. Run static validation first
uip rpa validate --file-path "MyWorkflow.xaml" --output json
# 2. If 0 static errors, start a debug session to validate runtime behavior
uip rpa debug start --file-path "MyWorkflow.xaml" --output json
# 3. Continue past the fixed area and inspect variable state
uip rpa debug continue --output json
# 4. Check the response for:
# - Helm: Data.hasErrors false AND Data.errorMessage null AND Data.debugState null/"Completed";
# Studio Desktop: Data.errors empty AND Data.output == "Session ended" —
# the pass/fail signal; the outer Result stays "Success" for a suspended debug session
# - Data.output (workflow's serialized output args) carries the expected values
# - Streamed [Level] log lines above the envelope are diagnostic context, NOT a failure signal —
# Error/Warning levels there are workflow-emitted observability, not CLI failures
# 5. Cancel
uip rpa execution cancel --output json
6. Debugging with Input Arguments
Pass input arguments when the workflow has In arguments that need values:
# Start debugging with input arguments — one key=value pair per flag occurrence
uip rpa debug start --file-path "ProcessOrder.xaml" \
--input-arguments orderId=ORD-12345 \
--input-arguments customerEmail=test@example.com \
--output json
--input-arguments is valid with run, debug start, debug test-activity, and debug start-from-here. For run / debug start, = keeps the value a string and := passes raw JSON (retries:=3, enabled:=true). For debug test-activity / debug start-from-here, values must be VB/C# expressions — always =. Full grammar (file payloads, quoting rules): cli-reference.md § Passing structured inputs.
Profiling Workflow Performance
Use --profiling on a start verb to collect per-activity timings and runtime screenshots — the same data Studio's Profile Execution tool surfaces. Profiling serves two purposes that can be addressed in a single run: verifying UI automation correctness (via the captured screenshots — confirm clicks landed on the right element, forms filled as expected, screens transitioned correctly) and verifying workflow performance (via the per-activity timings). The executor writes *.uistat files plus screenshots into %LOCALAPPDATA%\UiPath\ProfiledRuns\HHmmss_yyyy-MM-dd_<entryPoint>_<projectName>\ and the response carries the absolute path on Data.profiling.outputDirectory (§ Output Format).
When to enable profiling
| Situation | Why |
|---|---|
| User reports a slow workflow ("X takes 5 min, was 30 s last week") | Profiling localizes the regression to specific activities instead of the whole workflow |
| Choosing between two implementations of the same logic | Compare cumulative time across the activities each version uses |
| A loop body looks expensive but the cost is not obvious | *.uistat reports execution count + min/max/avg per activity — flags hot iterations |
| Pre-production sanity check on a long-running automation | Catches an activity whose individual time looks fine but whose cumulative share is dominant |
| Verifying a UI automation ran correctly without re-running it interactively | Captured screenshots show what the workflow actually saw at each UI activity — confirms clicks landed, forms filled, screens transitioned |
| Diagnosing "the workflow succeeded but the wrong thing happened" | Cross-check screenshots against expected screens; cheaper than rerunning with a debugger attached |
Do not enable profiling by default. It is opt-in for performance investigations and UI correctness checks — a normal smoke test (uip rpa run) is faster and produces no .uistat files or screenshots to clean up.
Where the flag is effective
Only start verbs collect profiling — --profiling is silently ignored on stepping/breakpoint verbs:
| Verb | --profiling effect |
|---|---|
run |
Collects |
debug start |
Collects |
debug test-activity |
Collects (single-activity scope; useful for tuning one activity). Studio Desktop required (depends on focus-activity). |
debug start-from-here |
Collects (partial workflow from the focused activity onward). Studio Desktop required (depends on focus-activity). |
debug step-over / step-into / step-out / continue / break / resume / continue-retry / continue-ignore / restart-from-top / toggle-breakpoint / execution cancel |
No-op |
Reading the result
uip rpa run --file-path "ProcessOrders.xaml" --profiling --output json
Read Data.profiling.outputDirectory:
{
"output": "{\"orderCount\":42}",
"hasErrors": false,
"errorMessage": null,
"profiling": {
"outputDirectory": "C:\\Users\\<user>\\AppData\\Local\\UiPath\\ProfiledRuns\\142305_2026-05-12_Main.xaml_ProcessOrders"
}
}
The directory contains *.uistat files — one per workflow file executed in the run (top-level entry point plus every invoked workflow) — alongside runtime screenshots captured at UI activity boundaries. Each *.uistat row reports an activity with execution count, min / max / average / cumulative duration, and the cumulative percentage of total run time. Focus on:
- Activities with the largest cumulative percentage — the dominant time sinks. Optimize these first.
- High execution count × moderate average duration — typically loop bodies. Consider batching, caching, or hoisting work out of the loop.
- Wide min/max spread on a UI activity — flaky selectors or variable target-element resolution; cross-check with the healing-agent log and the screenshot for that activity to confirm the element actually rendered.
- Screenshots for UI correctness — open the screenshot folder to verify each UI interaction targeted the expected screen / element. Useful when the workflow reports
Successbut downstream data looks wrong.
Caveats
profilingisnullwhen the run did not reach the executor (compile failure surfaces inerrorMessageinstead) or when the active Studio profile does not support profiling (non-Develop profiles register a no-op profiling service). Check it before readingoutputDirectory.- Numbers from a
debug startprofile run differ from arunprofile run — the debugger adds tracking overhead. For perf comparisons, always userun. - Files are not auto-cleaned. After an investigation, manually clear
%LOCALAPPDATA%\UiPath\ProfiledRuns\if disk usage matters. - Profiling is per run, not aggregated across runs. To compare two implementations, run each with
--profilingseparately and diff the*.uistatreports. - Studio's profiling tool window does not auto-focus on agent-triggered runs (intentional — profiling panel and Autopilot pane share a dock slot). Direct the user to
profiling.outputDirectoryon disk; do not tell them "open the profiling panel".
Activity-targeted profiling needs Studio Desktop.
debug test-activityanddebug start-from-herecollect profiling fine, but they depend onfocus-activity— which only runs against Studio Desktop.runanddebug startprofile on both Studio Desktop and headless (Helm). See Studio Desktop vs headless.
Reading Debug Output Effectively
Read the response in this order (fields per § Output Format; the Helm shape is described — on the Studio Desktop shape the verdict is errors empty AND output == "Session ended", and the log lines are the logEntries array). Verdict comes from Data — never from the outer Result alone, and never from log-line levels.
hasErrors+errorMessage+debugState— the success/failure signal. Passed only whenhasErrorsisfalse,errorMessageisnull, anddebugStateisnullor"Completed". The outerResultqualifies the CLI call, not the run:Failurefor a faultedrun(fields JSON-encoded inMessage),Successfor a suspended debug session.errorMessage(whenhasErrors: true) — formatted chain with the source activity, exception type, message, and stack trace. This is the canonical failure diagnostic. WithhasErrors: falseanddebugState: "Suspended"it carries command guidance instead; the exception is indebugDetails.output(whenhasErrors: false) — workflow's serialized output arguments JSON forrun/debug startcompletions ("{}"when none are declared).""while a session isPaused/Suspended/Running, ondebug state, and when the run never started (validation failure, missing entry point);"{}"on a run that faulted inside an activity.- Log lines — diagnostic context, streamed live as
[Level] messagelines above the envelope. Use them to read variable values the workflow logged, trace ordering, or correlate context with anerrorMessagethat already failed the run. Do NOT use a log line's level as a failure signal.
Identifying the Root Cause from Debug Output
A practical example — a workflow makes an HTTP request and tries to deserialize the response as JSON, but fails:
hasErrors: truewitherrorMessagecarryingJsonReaderException: Unexpected character encountered while parsing value: T— the deserializer tried to parse a non-JSON response- Streamed log entries (or workflow
Log Messageactivities) reveal the HTTP response variable hadStatusCode: "TooManyRequests"andTextContent: "Too Many Requests\r\n"— the API returned a 429, not JSON - Fix: Add status code checking before deserialization, or add retry logic with backoff to the HTTP request
Best Practices
- Always use
--output jsonfor debug verbs when you need to parse the output programmatically. The structured output makes it easy to inspect variables and identify exceptions. - Set breakpoints strategically — place them just before the activity you suspect is failing, not at the very start. This avoids stepping through dozens of unrelated activities.
- Prefer
--breakpointsondebug start— it targets specific activities by their XAMLIdRefwith no focusing step and runs headless. Usefocus-activity+debug toggle-breakpointonly for interactive sessions on Studio Desktop. - Never let a debug response go unread — every command returns
DebugState; branch on it (Paused→ inspect and step,Suspended→ decide on the exception,Running→ polldebug stateorbreak,Completed→ read the run result). - Use
debug test-activityfor quick feedback — it runs a single activity in isolation, which is faster than debugging the entire workflow. Studio Desktop required (depends onfocus-activity). Pre-set variables with--input-variablesso the activity has the data it needs. - Use
debug start-from-hereto skip setup — when the bug is deep in the workflow, skip straight to the relevant activity instead of stepping through the entire flow. Studio Desktop required (depends onfocus-activity). Pre-set variables with--input-variablesto simulate the state the activity would have received from preceding activities. - Prefer
debug step-overfor quick inspection — it moves one activity at a time without descending into scopes. Usedebug step-intoonly when you need to examine what happens inside a loop iteration or nested sequence. - Check variables after each step — every
Paused/Suspendedresponse carries a locals snapshot (in-scope variables, arguments, current activity properties) inDebugDetails; streamed log entries remain useful for values the workflow logged along the way. - Use
debug continue-retryfor transient errors — if the exception is a network timeout or rate limit, retrying may succeed without any code changes. - Use
debug continue-ignorecautiously — it skips the exception, which may leave variables in an unexpected state for downstream activities. - Cancel the session when done — always issue
execution cancelto cleanly end the run or debug session. - Use
--log-level Verbosewhen you need maximum detail about what the workflow is doing between steps. - Remember expression syntax for variables — when using
debug test-activityordebug start-from-here, string values need VB/C# string literal quotes inside the JSON value (e.g.,"\"hello\""not"hello"). - Reach for
--profilingwhen investigating performance or verifying UI automation correctness — pair it withrunfor production-like numbers (the debugger adds overhead). Read the response'sprofiling.outputDirectory: open the*.uistatfiles starting with activities holding the largest cumulative percentage, and inspect the captured screenshots to confirm each UI interaction landed on the expected screen / element. See Profiling Workflow Performance.
Open this reference as its own page
Environment Setup
Goal: Resolve the project root before any other operations.
<!--skill-flavor:host-scope:start--> <!--skill-flavor:host-scope:end-->Studio Desktop vs headless Studio
uip rpa uses headless Studio (Helm, shipped as UiPath.Studio.Helm.{Platform} NuGet package and auto-launched when needed) by default. Studio Desktop is unnecessary for the standard authoring loop (init, run, debug start, validate, build, activities find, packages install, and uia indication/capture/interaction). It is required only for uip rpa files diff and uip rpa focus-activity; see § Edge case: requiring Studio Desktop.
The first invocation may silently restore Helm for 30–90 seconds (longer behind a slow feed); a heartbeat every 15s confirms progress. The default shell timeout covers this; increase timeoutSeconds only behind a slow feed.
Step 0.1: Establish Project Root
uip rpa targets the current directory unless --project-dir is supplied; a non-root CWD causes failure or targets the wrong project. Resolve in order:
- User-provided directory: use it as-is.
- Named project: search for a same-named folder containing
project.json. - Otherwise use the CWD.
If the CWD is not the root, locate it with Glob: pattern="**/project.json", pass --project-dir explicitly to every uip rpa command, and store it consistently as {projectRoot}.
Step 0.2: Authentication (If Needed)
For IS connections, workflow examples, or cloud features, run:
uip login
For 401, 403, or “not authenticated” errors, prompt the user to run uip login against their UiPath Cloud tenant.
Step 0.3: Creating a New Project
ALWAYS use uip rpa init; never manually write project.json, project.uiproj, or scaffolding files. init always scaffolds XAML: BlankTemplate → Main.xaml, TestAutomationProjectTemplate → TestCase.xaml, and LibraryProcessTemplate → XAML library workflows. No flag changes scaffolding to coded. --expression-language controls VB/C# syntax inside XAML, not coded workflows; .cs workflows with [Workflow]/[TestCase] work in both VisualBasic and CSharp projects.
For coded mode, run the same XAML init, then add .cs workflows using coded/operations-guide.md § Add a Workflow File and update entryPoints in project.json. XAML and coded workflows may coexist; retain scaffolded Main.xaml/TestCase.xaml unless the user explicitly requests coded-only.
Choose the template using § Template selection before init; use BlankTemplate only when no template or domain pattern was named.
For XAML Projects (default for new projects)
uip rpa init \
--name "MyAutomation" \
--location "/path/to/parent/directory" \
--template-id "BlankTemplate" \
--expression-language <VisualBasic|CSharp> \
--target-framework <Windows|Portable> \
--description "Automates invoice processing" \
--output json
Decide and pass both --target-framework and --expression-language; never omit them. They are immutable after creation. Omitting --target-framework silently creates Windows. The new-project options shown here are Windows and Portable; Windows - Legacy is a last resort for an explicit ask or hard .NET 4.6.1 need and must be created/authored in Legacy mode, not through this command. Choose from runtime/host-OS signals per SKILL.md Common Rule 2a.
Inside a solution folder, init registers the new project in the enclosing .uipx; pass --skip-solution-registration for a project that stays out of the solution, such as a scratch or probe project.
--expression-language defaults to VisualBasic; use CSharp only when explicitly requested for C# expressions in XAML. Headless Studio needs no --studio-dir; pass it only when Studio Desktop is explicitly forced (UIPATH_RPA_TOOL_USE_STUDIO=1, or diff/focus-activity) and registry auto-detection fails.
For Coded Projects (only when the user explicitly requested coded)
Run the same command above; there is no separate coded form. Then add .cs workflows per coded/operations-guide.md § Add a Workflow File and update entryPoints.
Parameters
| Parameter | Options | Default | Notes |
|---|---|---|---|
--name |
Any string | required | Project folder name |
--location |
Directory path | current dir | Parent directory |
--template-id |
BlankTemplate, LibraryProcessTemplate, TestAutomationProjectTemplate |
BlankTemplate |
Project template |
--expression-language |
VisualBasic, CSharp |
none—set explicitly | XAML expression syntax; immutable |
--target-framework |
Windows, Portable (Cross-platform), Legacy (Windows - Legacy) |
none—set explicitly (omitting → Windows) | Immutable; Legacy only as a last resort per Rule 2a |
--description |
Any string | none | Description in project.json |
--skip-solution-registration |
flag | off | Inside a solution folder, leaves the project out of the .uipx |
uip rpa init may return success: false while creating files. On failure, check for the project directory and project.json before retrying.
Template selection
Before init, apply these rules:
| User says... | Action |
|---|---|
| "REFramework", "ERP template", "SAP template", "based on X template", or any specific template name | Run uip rpa templates search --query "<term>" --output json (see § "Search and select" below) |
| "library", "library project" | Use --template-id LibraryProcessTemplate (built-in, no search) |
| "test project", "test automation" | Run uip rpa templates search --query "Test Automation Framework" --output json and create from the Official Test Automation Framework template (testing-guide.md § Test Automation Framework); --template-id TestAutomationProjectTemplate (built-in, no search) only when the user asks for a blank test project |
| Nothing template-related | Use --template-id BlankTemplate (default) |
Search and select
Run uip rpa templates search --query "<term>" --output json and evaluate Data[*] top-down:
- If the user named a specific non-Official template (e.g. "Enhanced REFramework", "Lite ReFrameWork", a specific package name) and a
Marketplaceitem’stitleorpackageIdsubstring-matches that qualifier ("Enhanced", "Lite", etc.), ask the user and treat the Official item plus that Marketplace item as candidates; do not auto-pick. - If exactly one
source == "Official"item exists and no non-Official template was named, pick it without prompting. - Multiple
Officialitems → present candidates (packageId,version,title,description) and ask the user. - Zero
Officialitems, ≥1Marketplaceitem → present and ask. Never silently pick a Marketplace template. - For no results, tell the user and create with
--template-id BlankTemplate.
For a selected Official/Marketplace template, pass --template-package-id and optionally --template-package-version (omit it for latest) to init; when --template-package-id is set, --template-id is ignored.
From a NuGet Template Package
Use this when the user requests a domain-specific or named package, or wants to browse templates. Run:
uip rpa templates search --query "<SEARCH_TERM>" --output json
This needs no open project and returns a JSON array of TemplateSearchResult objects with fields packageId, version, title, description, authors, source, and tags (an array). --query is a string filter (omit to list all); --limit is an integer, default 20; --include-prerelease is a flag, default false.
[
{
"packageId": "UiPath.Template.SAPExample",
"version": "2.0.0",
"title": "SAP Automation Template",
"description": "Pre-configured project for SAP GUI automation",
"authors": "UiPath",
"source": "https://feed.example.com/v3/index.json",
"tags": ["SAP", "ERP"]
}
]
Create from the chosen package with:
uip rpa init \
--name "MySAPAutomation" \
--location "/path/to/parent/directory" \
--template-package-id "<PACKAGE_ID>" \
--template-package-version "<VERSION>" \
--target-framework <Windows|Portable> \
--expression-language <VisualBasic|CSharp> \
--output json
Pass --target-framework and --expression-language here too (Rule 2a). --template-package-id is a NuGet ID and overrides --template-id; --template-package-version defaults to latest and may be omitted.
After Creation
- Run
uip rpa project open --project-dir "/path/to/MyAutomation". - Read the scaffolded files before editing.
- Continue with the new project root.
Batch reading scaffolded files, packages install for known-needed packages, and the first activities find as parallel tool calls in one message; they depend only on project existence and share the warmed host. See SKILL.md § Execution Maps and execution-maps-guide.md.
Edge case: requiring Studio Desktop
Only these commands require a running Studio Desktop instance:
| Command | Behavior |
|---|---|
uip rpa files diff |
Opens an interactive diff window and finishes when the user closes it |
uip rpa focus-activity |
Selects/highlights an activity in the active designer; against headless it silently succeeds without doing anything, so success: true does not prove focus |
When needed, run:
uip rpa instances list --output json # hidden diagnostic — confirms a Studio Desktop instance is running
uip rpa studio start --project-dir "{projectRoot}" --output json # launches Studio Desktop if none is running
If registry resolution fails, pass --studio-dir with the Studio installation root. You may force Studio for any command with UIPATH_RPA_TOOL_USE_STUDIO=1, but this is unnecessary for standard authoring and loses headless benefits.
If studio start fails with does not support rpa-tool or Requires Studio <MIN_VERSION>+, this Studio has no rpa-tool interop. Do not retry; continue headless per cli-reference.md § Headless Studio (Helm) vs Studio Desktop instead of asking the user to upgrade.
Project Structure Reference
Directory Layout
MyProject/
├── project.json # Project manifest (name, dependencies, settings)
├── Main.xaml # Default entry point (XAML mode) ─┐ typically one
├── Main.cs # Default entry point (coded mode) ─┘ or the other
├── *.xaml # Additional XAML workflow files
├── *.cs # Coded workflows, test cases, and source files
├── *.cs.json # Auto-generated by Studio — do not create manually
├── ~*.xaml, ~*.cs # Studio Desktop backup of an open file's unsaved changes — not a workflow (§ Rules, Rule 5)
├── .codedworkflows/ # Auto-generated coded workflow support files (ConnectionsFactory.cs, ConnectionsManager.cs, ISConnections.cs, etc.)
├── .entities/ # Data Fabric entity manifest — EntitiesStore.json. Committed; source of truth for which entities are bound to the project. Managed via uip rpa data-fabric-entities install.
├── .local/ # Local cache (package restore, compiled artifacts)
│ ├── install/ # Restored NuGet packages
│ ├── docs/ # Auto-generated activity documentation
│ │ └── packages/ # Per-package doc folders
│ ├── .codedworkflows/ # Auto-generated (ObjectRepository.cs, CodedWorkflow.cs, WorkflowRunnerService.cs)
│ └── .entities/ # Compiled Data Fabric entity assemblies (DataService.<Namespace>.dll) per install signature. Regenerated on demand — do not edit.
├── .objects/ # Object Repository metadata (UI element selectors)
├── .project/ # Project metadata
│ ├── JitCustomTypesSchema.json # JIT-compiled custom type definitions
│ └── PackageBindingsMetadata.json
├── .screenshots/ # Activity screenshots (auto-generated)
├── .settings/ # Project-level settings
├── .autopilot/ # Autopilot service specific files
│ └── skills/ # Project-specific Autopilot skills
└── .storage/ # Activity resource storage (bucket-organized)
├── .design/ # Design-time only resources (NOT packed into published package)
│ └── <bucket>/ # Named bucket to prevent conflicts
└── .runtime/ # Runtime resources (packed into published NuPkg)
└── <bucket>/ # Named bucket with resource files
Coded-Only Elements
.cs files with [Workflow]/[TestCase]; auto-generated .cs.json files (never create manually); .codedworkflows/ and .local/.codedworkflows/ support files when .cs exists; and .variations/ data-driven test parameters for Tests projects.
XAML-Only Elements
.xaml workflow files and project.json expression language (VisualBasic or CSharp).
project.json Key Fields
{
"name": "MyProject",
"description": "",
"main": "Main.xaml",
"dependencies": {
"UiPath.System.Activities": "[24.12.1]"
},
"schemaVersion": "4.0",
"studioVersion": "25.0.0.0",
"projectVersion": "1.0.0",
"runtimeOptions": {
"autoDispose": false,
"netFramework": { "targetFramework": "net6.0-windows" },
"isPausable": true,
"isAttended": false,
"requiresUserInteraction": false
},
"designOptions": {
"projectProfile": "Developement",
"outputType": "Process",
"libraryOptions": {
"includeOriginalXaml": false,
"privateWorkflows": []
}
},
"expressionLanguage": "VisualBasic",
"entryPoints": [
{
"filePath": "Main.xaml",
"uniqueId": "2f510550-3882-4340-9239-53a24d0717f6",
"input": [],
"output": []
}
],
"targetFramework": "Windows"
}
Important meanings: name is the package-output name; main is the relative default workflow; dependencies contains NuGet constraints; expressionLanguage is immutable CSharp or VisualBasic and defaults to VisualBasic; designOptions.outputType is Process, Library, or Tests; targetFramework is Windows (.NET 6 Windows-only), Portable (Cross-platform .NET 6+), or Legacy (Windows - Legacy, .NET Framework 4.6.1), selected explicitly at init; and entryPoints contains per-workflow metadata only for Process projects—Tests and Library projects use empty [].
Rules
- Use CLI for dependencies: Always use
uip rpa packages installto add/update dependencies; never manually editdependenciesinproject.json. - Do not edit
.local/or.objects/: They are build-managed. mainentry point: It runs by default when unspecified;entryPointsis populated only for Process projects, while Tests and Library use[].--project-dirawareness and project creation: See § Step 0.1 and § Step 0.3.~<name>files are Studio Desktop backups, not workflows. While a file is open in Studio Desktop with unsaved changes, Studio writes the designer's in-memory copy beside it as~<name>(~Main.xaml,~Process.cs) every few seconds and marks it hidden;findandlsstill list it. Studio deletes it when the file is saved or Studio closes cleanly, and after a crash offers to recover it on the next project open.buildandpackexclude every~*file, and Studio's Git integration and project tree skip them.- Exclude
~*when listing or counting workflows:find "<PROJECT_DIR>" -name "*.xaml" -not -name "~*". Never read one as source, edit, validate, invoke, or register it inproject.json. - Never delete, rename, or move one: Studio owns it, and it is the user's only copy of their unsaved designer work.
- Never stage or commit one. The
.gitignorepattern that keeps them out of a repository is~*. - Its presence means Studio Desktop holds
<name>with changes that are not on disk, and whichever copy is saved last overwrites the other. If~<name>exists before your first edit of<name>this session, the unsaved changes are the user's: ask them to save or discard<name>in Studio before you edit it. If it appeared only after your own edits or runs, continue, and in the final report tell the user that Studio Desktop holds unsaved changes to<name>and that saving them there overwrites your edits on disk.
- Exclude
Common Activity Packages
| Package ID | Description | Key Activities |
|---|---|---|
UiPath.System.Activities |
Core system | Assign, If, ForEach, While, Invoke Workflow, Log Message, Delay |
UiPath.UIAutomation.Activities |
UI interaction | Click, Type Into, Get Text, Open Browser, Use Application/Browser |
UiPath.Excel.Activities |
Excel | Read Range, Write Range, Read Cell, Write Cell, Format Range |
UiPath.Mail.Activities |
Send Mail, Get Mail, Save Attachments, Forward Mail | |
UiPath.Database.Activities |
Database | Execute Query, Execute Non Query, Connect, Disconnect |
UiPath.WebAPI.Activities |
HTTP/REST | HTTP Request, Deserialize JSON, Serialize JSON |
UiPath.PDF.Activities |
Read PDF Text, Read PDF with OCR, Extract Data From PDF | |
UiPath.Word.Activities |
Word | Read Text, Replace Text, Insert Image, Export to PDF |
UiPath.Testing.Activities |
Testing/assertions | Verify Expression, Verify Are Equal, Generate Test Data |
UiPath.Presentations.Activities |
PowerPoint | Add Slide, Replace Text, Insert Image |
UiPath.IntegrationService.Activities |
Integration Service connector runtime | Generic connector activities for Salesforce, ServiceNow, HubSpot, etc. |
UiPath.Cryptography.Activities |
Encryption/hashing | Encrypt Text, Decrypt Text, Hash File |
Version Constraints
Dependencies use NuGet constraints: [1.0.0] means exact version; [1.0.0, ) means 1.0.0 or higher; [1.0.0, 2.0.0) means 1.0.0 inclusive through below 2.0.0.
Designing Project Structure
Proactively design files for task complexity; do not put everything in one root workflow. For coded versus XAML, see coded-vs-xaml-guide.md; new projects default to XAML.
Guidelines
- One simple task may use one root workflow (
Main.xamlorMain.cs). - A multi-step process uses a root orchestrator plus one workflow per step.
- Put shared data structures in Coded Source Files such as
Models.csorInvoiceData.cs; XAML cannot define types. - Put repeated logic in reusable XAML workflows, or helper Coded Source Files in coded/hybrid projects.
- Use one test case per scenario. Coded tests may use
partial class CodedWorkflow : CodedWorkflowBase, IBeforeAfterRuninCodedWorkflowHooks.cs; XAML tests use Test Activities for shared setup. - Isolate complex business rules in typed Coded Source Files or activity-driven workflows for reuse and testing.
Designing for Reuse
Single responsibility
One workflow file performs one meaningful action and is named for it (ProcessInvoice.xaml, LoginToApplication.xaml). Split at roughly 20–30 activities. What remains inline follows SKILL.md Common Rule 4b.
Standard folder shape
For multi-step processes use this shape:
Project/
├── Main.xaml # High-level orchestration only
├── Framework/ # Init, cleanup, error handling, app open/close
├── BusinessLogic/ # Process-specific rules and transactions
├── Utilities/ # Process-agnostic helpers (formatters, screenshots)
└── Data/ # Config files, templates
Separate business logic from UI components
UI workflows interact with applications and contain no business rules; business workflows decide and never touch UI. Keep reads and writes distinct (for example, GetCustomerInfo.xaml and ChangeCustomerInfo.xaml) so UI changes and business-rule changes remain independent. Promote process-agnostic UI components to shared libraries when useful.
Composition and argument naming
Compose with Invoke Workflow File (coded: workflows.StepName()). Argument names follow SKILL.md Common Rule 4c.
Layout and scale-out
Choose Sequence, Flowchart, or State Machine per xaml/xaml-basics-and-rules.md § Workflow Types. Use dispatcher/performer queues for high-volume transactions: reframework-guide.md § Execution Mode: Queue-Driven.
Promotion ladder
Promote only as reuse appears: inline → separate workflow file → shared library (library-authoring-guide.md) → UI Library for shared selectors (uia-policies-catalog.md § Object Repository as a Published UI Library).
Example — Invoice Processing Project (XAML)
InvoiceProcessor/
├── project.json
├── Main.xaml # Root workflow: sequences each step via Invoke Workflow File
├── ReadInvoices.xaml # Step 1: reads invoices from Excel
├── ValidateInvoices.xaml # Step 2: validates data
├── PostToERP.xaml # Step 3: posts to external system
└── InvoiceData.cs # Coded source file: typed data model used across XAML steps
Main.xaml invokes each step via Invoke Workflow File, passing arguments In/Out. InvoiceData.cs is included even in this otherwise-XAML project because XAML cannot define types — typed DTOs eliminate DataTable column-name guessing.
Coded equivalent
InvoiceProcessor/
├── project.json
├── Main.cs # Root workflow: calls each step via workflows.StepName()
├── ReadInvoices.cs # Step 1
├── ValidateInvoices.cs # Step 2
├── PostToERP.cs # Step 3
├── InvoiceData.cs # Coded source file: data model
└── ValidationHelpers.cs # Coded source file: validation utilities
Main.cs uses strongly-typed workflow invocation:
[Workflow]
public void Execute(string inputFolder)
{
var readResult = workflows.ReadInvoices(folderPath: inputFolder);
Log($"Read {readResult.count} invoices");
var validateResult = workflows.ValidateInvoices(invoices: readResult.invoiceList);
Log($"Valid: {validateResult.validCount}, Invalid: {validateResult.invalidCount}");
var postResult = workflows.PostToERP(validInvoices: validateResult.validInvoices);
Log($"Posted {postResult.successCount} invoices to ERP");
}
Example — Test Project
InvoiceTests/
├── project.json
├── CodedWorkflowHooks.cs # Coded test projects only: partial class CodedWorkflow with Before/After hooks
├── TestLoginFlow.cs # Test case: login scenario (hooks apply automatically via partial class merge)
├── TestInvoiceCreation.cs # Test case: create invoice scenario
├── TestInvoiceValidation.cs # Test case: validation rules
└── TestData.cs # Source file: shared test constants/fixtures
XAML test projects use .xaml test cases instead of .cs and Test Activities for shared setup; the rest of the layout is the same.
Example — Hybrid Project (XAML Root + Coded Logic)
OrderProcessing/
├── project.json
├── Main.xaml # XAML root workflow: sequences steps, handles retries
├── ScrapeOrderPortal.xaml # XAML: UI automation with visual selector builder
├── SendConfirmationEmail.xaml # XAML: Mail activities (straightforward)
├── ProcessOrder.cs # Coded workflow: 12 validation rules + LINQ transforms
├── OrderModels.cs # Coded source file: Order, LineItem, ValidationResult DTOs
├── TransformHelpers.cs # Coded source file: date parsing, currency conversion
└── TestProcessOrder.cs # Coded test case: unit tests for ProcessOrder logic
Why hybrid here
- ScrapeOrderPortal.xaml — UI automation benefits from XAML's visual selector builder and recording tools
- ProcessOrder.cs — Order validation has 12 business rules with nested conditions; coded C# is clearer and testable
- OrderModels.cs — Typed DTOs used by both XAML (via typed arguments) and coded workflows, eliminating DataTable column-name guessing
- SendConfirmationEmail.xaml — Simple Mail activity, no logic — XAML is the simpler choice
- Main.xaml — Orchestration is linear (scrape → process → email); XAML Sequence is readable
Data flow
Main.xamlinvokesScrapeOrderPortal.xaml→ returnsDataTablevia Out argumentMain.xamlinvokesProcessOrder.csvia Invoke Workflow File → passes raw data, returns validatedOrderobjectsMain.xamlinvokesSendConfirmationEmail.xaml→ passes validated order data
Project Structure Decision Tree
For new projects default to XAML unless the user explicitly says “coded” or names coded-specific triggers such as custom data models, complex algorithms, or unit tests on business logic. Use Main.xaml for XAML and Main.cs for coded. Then apply:
- Single simple task → one root workflow.
- Multi-step process → root invoking separate step files.
- Repeated data structures → Coded Source File, including in XAML projects.
- Shared logic → reusable XAML workflow or helper Coded Source File.
- Test project → one case per scenario; coded tests may use
CodedWorkflowHooks.csand partial classCodedWorkflow. - Complex business rules → isolate in Coded Source Files.
- UI automation plus complex non-UI logic → hybrid: XAML UI/orchestration, coded business logic/data models; see coded-vs-xaml-guide.md.
Project Conversion (expressionLanguage / targetFramework)
Rule 23 (SKILL.md) forbids changing either field in an existing project. Both are fixed at creation for every XAML file: changing expressionLanguage invalidates expressions; changing targetFramework invalidates package references and activity compatibility.
Do not convert in place. When conversion is requested: (1) confirm with the user; (2) copy the project to a temporary folder; (3) create a new project with uip rpa init --expression-language <VisualBasic|CSharp> --target-framework <Windows|Portable>; for Windows - Legacy create it in Legacy mode instead, not through modern init; (4) recreate every old workflow equivalently; (5) delete the temporary copy only after successful generation and user agreement.
Project Context Discovery
Before project work, check .claude/rules/project-context.md.
If it exists, read its first-line metadata <!-- discovery-metadata: cs=N xaml=N deps=N -->; count **/*.cs excluding .local/ and .codedworkflows/, **/*.xaml, and dependency keys in project.json; never count ~* Studio backups (§ Rules, Rule 5). For each count compute abs(current - stored) / max(stored, 1) * 100. If any individual count differs by 60–70% or more, run discovery; otherwise proceed.
If absent, run the skip gate below; if it does not trip, run the discovery flow.
Skip gate: nothing to discover yet
Do NOT spawn the discovery agent when any condition holds:
| Condition | Check |
|---|---|
| Greenfield | Step 0 found no project.json |
| Empty | **/*.xaml + **/*.cs, excluding dot-directories, obj/, bin/, and ~* Studio backups, counts 0 |
| Fresh scaffold | Count 1 and it is untouched Main.xaml process/template, NewActivity*.xaml library, TestCase.xaml test, or Main.cs coded, with no authored logic: empty root Sequence or only Comment activities, or empty coded Execute body |
For a tripped gate, write no context files now; proceed, then after the build write both context files yourself using the discovery-flow paths and AGENTS.md marker logic.
Discovery flow
For missing or stale context:
- Spawn the project discovery agent and wait. Its definition is
../agents/uipath-project-discovery-agent.md. Use the registereduipath-project-discovery-agentwhen available; otherwise spawn a subagent with that file as instructions/custom skill and write access. Read-only is allowed via step 3. - The agent writes context files and returns a
context-files:status line plus the document. Use that document for this session; do not reread or rewrite files it wrote. - Only when it returns
context-files: not-written(read-only host or write error), write the returned content to both.claude/rules/project-context.md(create.claude/rules/) and rootAGENTS.md. IfAGENTS.mdhas<!-- PROJECT-CONTEXT:START -->/<!-- PROJECT-CONTEXT:END -->, replace only the marked content; otherwise append the fenced block. - If it returns
SKIP: <reason>, treat it as a gate trip: write no context files now and write them yourself after the build. - Proceed with the skill workflow.
Open this reference as its own page
Error Handling Guide
Production-grade error handling and resilience for modern UiPath projects (Windows / Cross-platform), XAML and coded. Covers exception taxonomy, Try/Catch, Retry Scope, ContinueOnError, Throw/Rethrow, screenshots, validation, Global Exception Handler (GEH), state recovery, transaction boundaries, idempotent/compensating writes, sensitive data, and retry ownership.
This guide owns the decision layer and resilience patterns. For mechanics:
- Raw
TryCatch/Throw/RethrowXAML shapes + Rule 24Sequencewrap → common-activity-card.md. ContinueOnError-swallow gotcha, Studio WebThrow.Exceptionround-trip,s:Exceptionalias → xaml/common-pitfalls.md.- Per-activity properties →
activity-docs/UiPath.System.Activities/<ver>/activities/{RetryScope,TryCatch,Throw,Rethrow}.md. - REFramework flow, queue retry,
MaxConsecutiveSystemExceptions→ reframework-guide.md. - C# expression-binding mechanics → xaml/csharp-activity-binding-guide.md.
- Long-running / persistence interplay → xaml/long-running-workflow-guide.md.
Legacy (.NET 4.6.1): use legacy/error-handling-guide.md. VB is primary; inline C# forms apply directly to .cs workflows; see § Coded.
1. Exception Taxonomy
Two families. Classify correctly — misclassification either wastes retries on bad data or skips recoverable failures.
| Business exception | System / Application exception | |
|---|---|---|
| Type | UiPath.Core.BusinessRuleException |
System.Exception (and any other subclass) |
| Cause | Invalid / missing INPUT DATA (bad format, missing field, rule violated) | Transient TECHNICAL failure (app crash, timeout, selector not found, network, file lock) |
| Retry fixes it? | No — data won't change on retry; needs a human | Maybe — transient, may clear on retry |
| Action | Log, skip item, mark failed | Retry (limited), reset app state, then escalate |
| Orchestrator queue Auto-Retry | Not retried | Retried (when enabled) |
BusinessRuleExceptionandSystem.ApplicationExceptionare siblings directly derived fromSystem.Exception; neither derives from the other.System.Exceptioncatches everything;BusinessRuleExceptiononly business exceptions.- Classification is never automatic: explicitly
Throw New BusinessRuleException(...). Other unhandled errors are system exceptions. - Qualify
UiPath.Core.BusinessRuleExceptionwhen ambiguous.UiPath.Coreis imported by default in new projects; use the full name in coded files or after compiler ambiguity. Check True/Check FalsethrowCheckpointException, notBusinessRuleException; validate business data withIf+Throw New BusinessRuleException(...).- Isolated invoke preserves type and properties. A workflow invoked with Isolated checked runs in its own executor, but the caller catches the original type and properties (
BusinessRuleExceptionremains one;FileNotFoundExceptionretainsFileName). Type-based Catch routing works across it; never route on human-readableMessage, which can change, localize, and contain variable data.
2. Choose the Mechanism
| Need | Use | Constraint |
|---|---|---|
| Handle/classify failure or compensate | Try/Catch | Wrap each externally interacting unit whose failure is handled differently, at step, transaction, or process level; not assignments/control flow. |
| Branch on UI presence | Check App State | Only when absence changes the next action, typically an optional popup. Not a guard before acting on the same element, page-load wait, or check that only throws for a later activity; use that activity's timeout and not-found failure (UIA package guide, Unnecessary Check App State). |
| Retry flaky action with success check | Retry Scope | Add a Condition verifying success; keep Action idempotent. |
| Reject bad input before work | Fail-fast + Throw New BusinessRuleException |
Validate all inputs up front (§7). |
| Tolerate expected non-critical failure | ContinueOnError=True |
Narrow use only (§6); never data/critical writes. |
| Centralized final logging/screenshot | Global Exception Handler | One per project; not a local Try/Catch replacement (§8). |
| Per-transaction retry and system/business split | REFramework | See reframework-guide.md. |
Default: fail fast on bad data; Try/Catch each differently handled external-interaction unit; Retry Scope for transient UI/network steps; GEH for centralized observability. Do not blanket-wrap pure logic or pre-check an element its activity will act on: its timeout waits and not-found error fails; handle that where behavior differs.
3. Try/Catch Discipline
Raw shapes and mandatory Sequence wrap: common-activity-card.md § TryCatch.
- Catch specific types before general types;
System.Exceptionlast. PutBusinessRuleException,TimeoutException, andSelectorNotFoundExceptionfirst; a precedingSystem.Exceptionmakes them unreachable. - Never leave Catch empty: this violates
ST-DBP-003. At minimumLog Messagethe exception in XAML and coded workflows. - Catch only failures you act on. Wrap external interactions, not an entire
Process.xamlcatch-all. Finallyis cleanup only: close/kill apps, dispose connections, delete temp files. No business logic. UseContinueOnError=Truefor best-effort cleanup so missing resources do not mask the original error.- A
TryCatchFinallyruns only when the exception is caught inside the same workflow file. An exception leaving the file—rethrow, throw from Catch, or never caught—skips that file's Finally regardless of invoking Catch, Invoke Workflow FileContinueOnError, orIsolated. Invoke Workflow File runs as a separate workflow instance; its unhandled exception ends that instance without those Finally blocks. A rethrow caught by an outer Try/Catch in the same file does run the inner Finally. If exceptions can escape, put mandatory cleanup/end logging at the end of Try and in every Catch before Rethrow, with aSystem.ExceptionCatch, or in the caller. - Do not design recovery around process termination. Out-of-memory, killed host processes, and UiPath fatal faults can prevent Catch/Finally; treat them as unrecoverable.
exception.Sourceis the activity type, not DisplayName, when Try/Catch and the failing activity share a workflow. To capture the failing step name, put it in its own workflow and wrapInvoke Workflow File.
4. Throw & Rethrow
Raw shapes: common-activity-card.md § Throw / § Rethrow. Throw.Exception is a constructor expression, not a string.
' Throw a business exception (build the message in an Assign first for complex text)
New BusinessRuleException("Invoice " & invoiceId & " amount " & amount.ToString("F2") & " is negative")
new BusinessRuleException($"Invoice {invoiceId} amount {amount:F2} is negative")
Rethrowpreserves original type and stack trace. Use it inside Catch after logging/screenshot to propagate unchanged. It is Catch-only; outsideCatch.Actionit throwsInvalidOperationException.- Never use
Throw New Exception(ex.Message)to resurface an error: it resets the stack and drops the type (CA2200). UseRethrow; useThrow New <Type>(...)only to translate types, such as wrapping a system error as business. - Put
Rethrowlast in Catch; later activities are unreachable. - Throwing a caught exception object (
Throwwith[storedException]) outside its Catch keeps its type, message,SourceandData, but restarts its stack trace; no analyzer rule flags it. It is the only way to raise the original exception once the handler has left the Catch, as a Flowchart's handler on the canvas does (xaml/canvas-layout-guide.md § Exception Handling Across Nodes). SetSource(or aDataentry) to the failing step first when a later handler reads it (§ 3 rule 7). Inside a Catch,Rethrowstays the rule.
5. Retry Scope
Properties (NumberOfRetries, RetryInterval, ContinueOnError, LogRetriedExceptions): activity-docs/UiPath.System.Activities/26.4/activities/RetryScope.md. It has an Action (ActivityBody) and optional Condition (ActivityFunc(Of Boolean)); retry occurs when Action throws or Condition returns False. Verified XAML shape (the property-element names aren't in the activity doc):
<ui:RetryScope NumberOfRetries="3" RetryInterval="00:00:05" DisplayName="Retry Scope">
<ui:RetryScope.ActivityBody>
<ActivityAction>
<Sequence><!-- activities to attempt (keep idempotent) --></Sequence>
</ActivityAction>
</ui:RetryScope.ActivityBody>
<ui:RetryScope.Condition>
<ActivityFunc x:TypeArguments="x:Boolean">
<!-- a Boolean-returning check (Element Exists, or Check True on a stored State).
Omit this whole block for exception-only retry. -->
</ActivityFunc>
</ui:RetryScope.Condition>
</ui:RetryScope>
xmlns:ui="http://schemas.uipath.com/workflow/activities" also supplies ui:LogMessage and ui:BusinessRuleException; a verified specific Catch is <Catch x:TypeArguments="ui:BusinessRuleException">. Equivalent CLR form: xmlns:uic="clr-namespace:UiPath.Core;assembly=UiPath.System.Activities" + uic:BusinessRuleException; either resolves.
Total executions equal NumberOfRetries, not 1 + retries: 0 = 0 (Action never runs; use 1 for one guaranteed run), 1 = 1, 3 (default) = 3 (one initial + two retries). =3 runs exactly three times then throws the last error; =0 is a no-op.
RetryIntervalis aTimeSpan, not seconds.3means 3 days; use00:00:05for five seconds (default00:00:05).- Condition semantics are inverse of a while loop:
Trueexits;Falseretries. Without Condition, retry is exception-driven and succeeds on the first error-free run. - Action reruns fully, so keep it idempotent.
Add Queue Item,Append Range,Write Range,Insert Rows, and payment/order POSTs can duplicate. Retry Scope has no deduplication; use an existence check or idempotency key. - Nest Retry Scope inside Try/Catch; after exhaustion it rethrows the last error to the outer Catch.
- Modern UI Automation
Click/Type Intohave built-in Verify execution retry; prefer it for one UI step and Retry Scope for multi-step blocks. In modern design,Check App Statecannot be directly in Condition; store itsStateto a Boolean and reference it. - In Orchestration Processes, Retry Scope and
Delayare unsupported inMain; wrap them inNo Persist Scope. - Attempts are nearly invisible by default:
LogRetriedExceptions=False, and enabledRetriedExceptionsLogLeveldefaults toTrace, below usual Orchestrator logging. Enable it and choose the level intentionally, or log attempt count yourself.
6. ContinueOnError
ContinueOnError=True suppresses a fault and continues where honored; the activity does not throw, so an enclosing Catch does not fire and failure is silent. It is not universal: some activities/exceptions ignore it; NetHttpRequest timeout is one example. Default is False; Workflow Analyzer UI-ANA-017 flags every True. See xaml/common-pitfalls.md.
- When Try/Catch is not catching, first inspect the activity or scope for
ContinueOnError=True. - On
Use Application/Browser,Attach,Retry Scope,On Element Appear, andTrigger Scope,Truecascades to all nested children, including intentional business throws. Set it on a specific child, never the scope, unless silencing the whole block is intended. - HTTP behavior:
- Modern HTTP Request (
NetHttpRequest): defaultContinueOnError=True. Network failure (HttpRequestException, including DNS/SSL/refused) becomes synthetic503inTextContentand does not throw; checkStatusCode. Timeout (TaskCanceledException) still throws. For critical calls setContinueOnError=False; network errors then propagate asHttpRequestException, and handle timeouts explicitly. (NetHttpRequest.md § ContinueOnError Behavior) - Classic
HttpClient: withTrue, errors are swallowed, response is unpopulated, andStatusCoderemains0; parsing the empty body can crash. SetFalse, or checkStatusCodebefore using the body. (HttpClient.md)
- Modern HTTP Request (
Allowed uses: Element Exists / Check App State (Boolean, no throw), best-effort cleanup in Finally, and a data-scrape next-page selector that disappears on the last page when paired with an existence check. Never use it on HTTP / DB write / file write / any output used downstream — silent failure → corrupt/empty data. Never use it on Invoke Workflow File when callee work or outputs matter: the caller continues as if complete with values set before failure, and callee Finally blocks did not run (§3 rule 5; see xaml/common-pitfalls.md § Out and InOut Arguments When the Callee Faults).
7. Fail-Fast Input Validation
Validate all required inputs in one Sequence at the start, before business logic. Catch every problem up front, not one run at a time. Don't validate inside loops — validate once before the loop. Immediately throw BusinessRuleException with the offending value; fail fast, fail loud, and do not let invalid data reach business logic.
If String.IsNullOrWhiteSpace(in_InvoiceNumber) Then Throw New BusinessRuleException("Invoice number is empty")
If in_Amount <= 0 Then Throw New BusinessRuleException("Amount must be positive: " & in_Amount.ToString())
8. Global Exception Handler (GEH)
The runtime invokes one project-wide handler when an activity faults. Use it for centralized logging/screenshots and a global retry/abort verdict, not instead of local Try/Catch.
Scaffold
Create a dedicated workflow with exactly two non-removable, case-sensitive arguments: errorInfo (In, ExceptionHandlerArgs) and result (Out, ErrorAction). Both types are in UiPath.Activities.Contracts; XAML alias: xmlns:uico="http://schemas.uipath.com/workflow/activities/contracts".
Verified scaffold:
<Activity x:Class="GlobalHandlerX"
xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities"
xmlns:ui="http://schemas.uipath.com/workflow/activities"
xmlns:uico="http://schemas.uipath.com/workflow/activities/contracts"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<x:Members>
<x:Property Name="errorInfo" Type="InArgument(uico:ExceptionHandlerArgs)">
<x:Property.Attributes><RequiredArgumentAttribute /></x:Property.Attributes>
</x:Property>
<x:Property Name="result" Type="OutArgument(uico:ErrorAction)">
<x:Property.Attributes><RequiredArgumentAttribute /></x:Property.Attributes>
</x:Property>
</x:Members>
<!-- Include standard TextExpression.NamespacesForImplementation / ReferencesForImplementation
(copy from any project .xaml) AND add UiPath.Activities.Contracts to the namespace list so
the ErrorAction enum resolves in expressions. -->
<Sequence>
<!-- log errorInfo.Exception, optionally screenshot, then set the verdict (verified Assign form): -->
<Assign>
<Assign.To><OutArgument x:TypeArguments="uico:ErrorAction">[result]</OutArgument></Assign.To>
<Assign.Value><InArgument x:TypeArguments="uico:ErrorAction">[ErrorAction.Abort]</InArgument></Assign.Value>
</Assign>
</Sequence>
</Activity>
The expression is imported ErrorAction.Abort, not uico:ErrorAction.Abort; uico: is XML-only and invalid in VB/C# expressions. ErrorAction resolves only when UiPath.Activities.Contracts is in NamespacesForImplementation.
errorInfo exposes Exception, ActivityInfo (.Name, .TypeName), RetryCount, Variables("name"), Arguments("name"), and WorkflowArguments("name").
Registration
Register in project.json under runtimeOptions:
"runtimeOptions": {
"exceptionHandlerWorkflow": "GlobalHandlerX.xaml"
}
- One per project; it cannot be
Main.xamland is unavailable for Library projects, which must use Try/Catch and propagation. - Removing it requires deleting the handler
.xamland removingexceptionHandlerWorkflowfromproject.json; otherwise registration points to a missing workflow.
Verdicts — ErrorAction
| Verdict | Effect |
|---|---|
Continue |
Re-throw; normal propagation/local Catch handles it. It does not mean skip. |
Ignore |
Suppress error and continue from the next activity. |
Retry |
Re-execute the failed activity. |
Abort |
Stop the job after the handler; the remaining Catch and Finally blocks do not run. |
Verdict logic — avoid the runaway loop
GEH re-enters at every call-stack level. Unconditional Retry can retry an always-failing activity indefinitely. Always gate it:
- Business data does not self-correct:
[TypeOf errorInfo.Exception Is BusinessRuleException]→result = ErrorAction.Abort. - Do not retry scaffolding:
[New HashSet(Of String)({"Throw","Rethrow","TryCatch","RetryScope","Sequence"}).Contains(errorInfo.ActivityInfo.TypeName)]→Continue(re-throw). [errorInfo.RetryCount < 2]→Retry; otherwiseAbort.
Interplay and limits
- GEH runs first-chance: before any local Catch — a Try/Catch around the faulted activity in the same workflow included — then again for every enclosing activity while the exception propagates. A local Try/Catch does not shield it, so a fault the workflow catches as normal flow still reaches the GEH first. Verified under
uip rpa run; see UiPath Global Exception Handler docs. - Fully unhandled: GEH fires and verdict applies; verified under
uip rpa run. - Activities with
ContinueOnError=Truenever reach the GEH. - GEH retries activities, not workflows; retry a whole workflow with your own loop / Retry Scope.
- Do not combine GEH with REFramework: their Try/Catch/retry strategies can fight and loop on business exceptions; choose one.
- During debugging, Studio pauses/highlights the activity and shows exception in Locals/Call Stack; ribbon offers Continue / Retry / Ignore / Abort. Debug Retry does not invoke GEH; only Continue does.
To verify GEH, run a workflow with an unhandled error—a Throw outside local Try/Catch. With registration, uip rpa run runs the handler, logs it, and honors verdict; e.g. returning Ignore skips the faulting activity and the run completes with hasErrors:false.
9. Screenshot-on-Error
Capture in Catch or GEH before propagating. Use Take Screenshot (UiPath.UIAutomationNext.Activities.NTakeScreenshot, package UiPath.UIAutomation.Activities).
- Use an absolute folder path ending
.png; relative paths resolve to the NuGet cache. Create the directory first. - Set capture
ContinueOnError=Trueso screenshot failure cannot abort the handler. - It requires an interactive session; unattended Robots without a display may fail (
Win32Exception 0x80004005) or write nothing. Prefer Orchestrator session recording (Robot 2023.2+) for reliable unattended post-mortems. - Screenshots routinely contain PII, credentials, invoices, and sessions. Use access-controlled storage, job/transaction id + timestamp names, retention/cleanup, and do not attach raw screenshots to broadly distributed logs.
10. Logging Exceptions
- Log
exception.ToString()(type, message, full stack), not only.Message; guard null:If(exception IsNot Nothing, exception.ToString(), "<missing>"). - Severity:
Errorfor caught system exceptions,Warnfor recoverable business exceptions,Fatalfor unrecoverable.Trace/Verbosecapture argument values and risk PII; do not log secrets. - Log before handling, including before Catch swallows or rethrows.
Log Messagetruncates at 10,000 chars; Automation Cloud drops robot logs over 50 KB. Orchestrator robot log level overrides local configuration; default isInformation.
11. Recover to a Known State Before Retrying
Before the next attempt after a system exception:
- Dismiss blocking popups/modal dialogs.
- Return app/browser to a known anchor (home/search); reattach, or close/reopen if gone.
- Clear partial form data and discard half-built records.
- Re-login after session expiry/timeout.
- Remove partial artifacts such as temp files and interrupted downloads.
- Verify the expected screen with
Check App State/Element Exists.
Put reset first in Retry Scope Action or in Catch before manual retry. A retry without state recovery is usually a bug.
12. Transaction Boundary (outside REFramework)
Handle one item, not the entire loop, so one bad item cannot abort the batch.
Queue-backed — Orchestrator owns retry: get item, process, then Set Transaction Status: Success on completion; BusinessException for bad data (no retry, human review); ApplicationException for transient/system failure (queue Max # of retries). Do not add a per-item retry loop; carry item Reference / id in every log line.
DataTable/list — own status and bounded retry:
For each row/item:
Try
Validate ' Throw BusinessRuleException on bad data
Process ' external interactions
Status column = "Success"
Catch BusinessRuleException ' bad data — do NOT retry
Status = "Failed: business"; log; continue to next item
Catch Exception ' transient — bounded retry of the SAME item, then escalate
Status = "Failed: system"; log
Finally
Persist the status column; release per-item resources
- One Try/Catch per item; one bad item must not abort the batch.
- Business exception: mark failed/skipped and continue. System exception: bounded retry of the same item, then escalate.
- Persist item status and release resources in Finally; include item id/correlation id in every log line.
13. Compensation & Resume-Safe Writes
- Use an idempotency key on API creates (client-generated id or
Idempotency-Keyheader). - Without one, check natural key before create. This is not concurrency-safe: two robots can both see nothing and create. Add server unique constraint/upsert, lock/reservation, or reconciliation; never rely on the check alone.
- Persist external id immediately after creation, before the next step, so resume continues instead of recreating.
- Never blindly retry non-idempotent writes (payment, append, keyless POST); see §5 rule 3.
- Define compensation for partial work: delete created draft, void transaction, or mark for manual reconciliation.
14. Sensitive Data in Logs & Screenshots
- Never log credentials, auth headers/tokens, full request/response bodies, bank/card numbers, full customer identifiers, or document images unless explicitly approved; redact or hash first.
exception.ToString()preserves stack detail, but its message may contain secrets/input values. Sanitize constructed messages; do not echo raw input.- Restrict screenshots, use id+timestamp names, retention/cleanup, and access control (§9).
Trace/Verbosecapture argument values; keep them out of production and preserve excluded-logged-data settings (Private:*,*password*).
15. Who Owns the Retry — Pick One Layer
Retries multiply: 3 local × 3 queue × 3 job can execute the same work up to 27 times and duplicate side effects. Assign one owner per concern.
| Layer | Owns | Not for |
|---|---|---|
Orchestrator queue retry (Max # of retries) |
Business-transaction retry with queues | Short UI blips |
| Retry Scope | Short transient retry around one flaky action | Whole transaction |
| Global Exception Handler | Central logging/screenshot and global verdict | Business-transaction retry (§8) |
| Orchestrator job/process retry | Whole-job restart, sparingly | Per-item/action retry |
- With queues, queue retry owns transaction retry; keep Retry Scope only for sub-second UI flakiness.
- Do not enable every layer; choose the lowest layer that fully resets state (§11) and disable the others.
Coded (C#)
Coded workflows use the same types and rules:
if (string.IsNullOrWhiteSpace(invoiceNumber))
throw new BusinessRuleException($"Invoice number is empty"); // using UiPath.Core;
try { /* external interaction */ }
catch (BusinessRuleException) { Log("business error", LogLevel.Warn); throw; } // bare throw = preserve stack
catch (Exception ex) { Log(ex.ToString(), LogLevel.Error); throw; }
Bare throw; preserves stack; throw ex; resets it—the same CA2200 rule as Rethrow versus Throw-new. Workflow Analyzer rules including ST-DBP-003 apply to .cs. For retry, use a plain for loop with try/catch and delay, or call Retry Scope from XAML. C# XAML binding: xaml/csharp-activity-binding-guide.md; coded using directives: coded/operations-guide.md § Using Statements Rules.
Anti-patterns
| Symptom | Cause | Fix |
|---|---|---|
| "Try/Catch isn't catching" | ContinueOnError=True on the activity/scope swallowed it |
Set False; check the enclosing scope too (§6) |
| "GEH isn't firing" | a local Try/Catch handled the exception (handled errors don't reach it; nested cases vary by version) | throw outside any local Catch to fire it (§8) |
| "Global handler infinite loop / runaway retries" | unconditional result = Retry |
Gate RetryCount, filter TypeName, Abort on BusinessRuleException (§8) |
| "Retry ran fewer times than expected" / "ran N, not N+1" | NumberOfRetries is TOTAL executions, not extra retries; 0 = no-op |
Set N = total runs wanted; 1 = one run (§5) |
| "RetryInterval waited days" | 3 parsed as 3 days |
Use 00:00:05 (§5) |
| "Duplicate rows / queue items after retry" | non-idempotent Action in Retry Scope | Existence check / idempotency key (§5) |
| "BusinessRuleException caught as system error" | not thrown explicitly, or namespace ambiguity | Explicit Throw New BusinessRuleException, qualify UiPath.Core (§1) |
Empty Catch |
silent failure, ST-DBP-003 |
Log at minimum (§3) |
Throw New Exception(ex.Message) to re-surface |
resets stack, drops type | Rethrow (§4) |
| Screenshot works attended, nothing unattended | no interactive session | Orchestrator recording + absolute path (§9) |
| Same work runs many times / duplicate side effects | retries stacked at multiple layers (local × queue × job) | one retry owner per concern (§15); idempotency on writes (§13) |
| Retry repeats the failure or corrupts data | action retried without resetting app/data state | recover to a known state first (§11) |
| Secrets/PII in logs or screenshots | logging raw messages/bodies; unprotected screenshot store | redact; restricted storage (§14) |
Open this reference as its own page
Execution Journeys Catalog — turn-budgeted build journeys
<!--skill-flavor:host-scope:start--> <!--skill-flavor:host-scope:end-->Catalog — read the one journey the task runs, never end-to-end: Grep ^## , then Read that journey through the next ## heading. What every journey shares — source precedence, gate versus runtime proof, sequential gates, failure exits, cross-session memory — is execution-maps-guide.md, read whole first.
Journey: Greenfield XAML (no UIA)
Skip project discovery: no project.json exists before T1, only the untouched scaffold after it (environment-setup.md § Skip gate). The parent-directory ls is the first link of T1's Bash chain, not a turn. Write project-context.md and AGENTS.md at T5.
| Turn | Emit in ONE assistant message |
|---|---|
| T1 — Scaffold + context | Run one Bash chain: uip rpa init --name "<NAME>" --location "<PARENT_DIR>" --template-id BlankTemplate --expression-language <VisualBasic|CSharp> --target-framework <Windows|Portable> --output json (Rule 2a; both flags explicit) && one uip rpa packages versions --package-id <PackageId> --include-prerelease --project-dir "<PROJECT_DIR>" --output json per request-known package && node -e "require('fs').rmSync(process.argv[1],{force:true})" "<PROJECT_DIR>/Main.xaml"; in parallel, plain full-Read xaml/xaml-basics-and-rules.md (Rule 22); Grep ^### on common-activity-card.md and common-pattern-card.md for their entries (Rule 21 card lookup); Grep ^## on xaml/common-pitfalls.md for headings (Rule 22, step 1); ask the package version question (execution-maps-guide.md § Sequential gates); recall memory; and fan out Rule 21 activities find for off-card activities. |
| T2 — Vet | In parallel, Read the card entries the plan needs, a card whole when it needs more than 5 of them (Rule 21); Read every xaml/common-pitfalls.md section whose T1 heading matches a planned activity, property, or feature; when unsure, read it (Rule 22, step 2); Read project.json; read needed xaml/xaml-editing-catalog.md entries for operations beyond the cards; and perform Rule 21 doc Reads plus get-default-xaml for off-card activities. Do not read Main.xaml; T1 deleted the scaffold. This is the only pitfalls-gate turn. |
| T3 — Author + install | For row processing, make the design fork first: complex bulk processing (per-row parse + validate + branch + accumulate) escalates to code per data-manipulation-guide.md § Code vs activity chains; the pattern card's ForEach shapes cover only the simple one-If/Switch case. Then Write one complete file per workflow (Rule 18), Edit project.json for fileInfoCollection test cases (Rule 10), and run ONE Bash uip rpa packages install for all needed packages at the versions T1's question settled, using cli-reference.md § packages install; on Invalid packages input, run uip rpa packages install --help again. dependencies remains CLI-owned. |
| T4 — Gate | Run one sequential Bash chain/loop for every edited file: uip rpa validate --file-path "<RELATIVE_FILE>" --project-dir "<PROJECT_DIR>" --output json per file && uip rpa build "<PROJECT_DIR>" --output json &&, when outputs are observable and no external system/UI is needed, uip rpa run --file-path "<RELATIVE_FILE>" --project-dir "<PROJECT_DIR>" --skip-build --output json on the entry point (--file-path required) && cat every requested output file. This output check is part of the chain. --file-path is relative to the project directory; absolute paths falsely fail due to a separator bug (cli-reference.md § validate). |
| T5 — Report | Send one message with no shell calls. Judge T4 verdict fields and cat output against the request; wrong/empty output with a clean gate indicates silent failure (execution-maps-guide.md § Failure exits). In that message, make parallel calls: Write .claude/rules/project-context.md and Write AGENTS.md with paths, metadata, and markers per environment-setup.md § Project Context Discovery step 3 (first line <!-- discovery-metadata: cs=N xaml=N deps=N -->; put the same block in AGENTS.md between <!-- PROJECT-CONTEXT:START --> / <!-- PROJECT-CONTEXT:END -->; do not Read/Grep first), qualifying memory Writes, and SKILL.md § Completion Output. Run nothing afterward. |
T1 is one message: init, every read, xaml/xaml-basics-and-rules.md, and the card and pitfalls heading Greps all ride together; only entry and section reads wait for T2. Do not open any other reference before T3, including environment-setup.md. The first chain call pays the cold Helm restore (30–90 s); do not split it to check progress. init may return success: false while creating files; check that project.json exists before retrying (environment-setup.md). Install dependencies only through packages install; never hand-edit project.json dependencies.
Repair cycle (validate/build failure): use one turn for an Edit fixing one root cause (Rule 19, Package first: a skipped packages install fails before activity issues), then one turn to rerun the batched gate. Card-covered failures do not reopen discovery; recheck the card. Retain each validation result and build only when all files are error-free. If >2 errors have ambiguous origin, bisect by stubbing half the new activities and re-validating. Maximum 5 attempts per loop (Rule 3).
Journey: Brownfield XAML edit
| Turn | Emit in ONE assistant message |
|---|---|
| T1 — Context | Run SKILL.md § Precondition context check: skip gate first, then the discovery subagent, which writes project-context.md + AGENTS.md (environment-setup.md § Project Context Discovery). In parallel, Read project.json, target .xaml, and xaml/xaml-basics-and-rules.md (Rule 22, plain full read); Grep ^### on common-activity-card.md and common-pattern-card.md (Rule 21 card lookup) and ^## on xaml/common-pitfalls.md; run packages versions in Bash for every package the edit uses; recall memory; and fan out off-card activities find. |
| T2 — Vet | Read the card entries the plan needs, a card whole when it needs more than 5 of them (Rule 21), matching xaml/common-pitfalls.md sections (Rule 22), needed xaml/xaml-editing-catalog.md entries, and off-card Rule 21 docs; ask the package version question when one is due (execution-maps-guide.md § Sequential gates). |
| T3 — Edit | Batch Edits, anchoring each on its own target block; same-file edits serialize and overlapping anchors fail. Run packages install in Bash at the versions T2's question settled. |
| T4 — Gate | Run one sequential Bash chain/loop covering every edited file: per-file validate with relative --file-path && build && optional run --file-path "<RELATIVE_FILE>" --skip-build && cat every output file, per execution-maps-guide.md § Gate ≠ runtime proof. |
| T5 — Report | Send one message with no shell calls: judge T4 verdict and cat output; emit SKILL.md § Completion Output and qualifying memory Writes in parallel. The discovery agent wrote context files in T1: do not read, edit, or rewrite them after the gate. The next session judges staleness by file/dependency counts (environment-setup.md § Project Context Discovery). If the skip gate tripped, write both files exactly as greenfield T5 does. |
Journey: Greenfield coded
init always scaffolds XAML; use the same command and flags as above, then add .cs files (environment-setup.md).
| Turn | Emit in ONE assistant message |
|---|---|
| T1 — Scaffold + context | Run ONE Bash chain: init with the XAML journey flags && packages versions per known package, and ask the package version question beside it (execution-maps-guide.md § Sequential gates). In parallel, Read assets/codedworkflow-template.md and coded/operations-guide.md § Coding Guidelines, then recall memory. |
| T2 — Author + install | Write each .cs (Rules 13–19); Read project.json; Edit it for entryPoints (Rule 15) and fileInfoCollection (Rule 10); run packages install in Bash; read .local/docs/packages/<PackageId>/coded/coded-api.md for installed services. |
| T3 — Gate | Run one sequential Bash chain/loop over every edited file: per-file relative---file-path validate && build && optional run --file-path "<RELATIVE_FILE>" --skip-build && cat every output file, per execution-maps-guide.md § Gate ≠ runtime proof. |
| T4 — Report | Send one message with no shell calls, using greenfield XAML T5's shape: judge T3 verdict and cat output, then parallel Writes for both context files, qualifying memory, and SKILL.md § Completion Output. |
Journey: Brownfield coded edit
Use the brownfield XAML journey with coded reads and no pitfalls-vet turn: T1 Read target .cs plus .local/docs/.../coded/coded-api.md for touched services, and packages versions for every package the edit uses; T2 Edits, plus the package version question when one is due; T3 packages install at the settled versions && gate; T4 report.
Journey: UIA capture + build (XAML)
Budget: ~4 fixed turns + ~3 turns per capture-screen + 2-turn debug cycle; a greenfield project adds T1–T2. Serialize capture across screens by application state (Complete-then-advance, the target-capture orchestration reference routed from the UIA package guide); never batch across an advance. Route concrete UIA CLI syntax through {PROJECT_DIR}/.local/docs/packages/UiPath.UIAutomation.Activities/ui-automation-guide.md § Documentation.
| Turn | Emit in ONE assistant message |
|---|---|
| T1 — Scaffold (greenfield only) | Run greenfield XAML T1's init chain with UiPath.UIAutomation.Activities among its packages versions calls, and ask the package version question beside it (execution-maps-guide.md § Sequential gates). In parallel, Read uia-starter-guide.md in full and plain full-Read xaml/xaml-basics-and-rules.md (Rule 22); Grep ^### on common-activity-card.md and common-pattern-card.md, and ^## on xaml/common-pitfalls.md. |
| T2 — Install (greenfield only) | Run ONE Bash packages install at the versions T1's question settled. The UIA package docs exist only after it, so T0 cannot share this turn. |
| T0 — Reads + pre-flight | In parallel, Read uia-starter-guide.md unless T1 read it, the UIA package core guide (Rule 7), and its mandated target-capture orchestration reference, all in full; check prerequisites (uia-starter-guide.md § UIA Prerequisites, Rule 7a); run ONE Bash window-baseline via the UIA snapshot CLI; build the element inventory/checklist from the user's manual steps. |
| Per capture-screen | Run the uia-configure-target flow once for ALL checklist elements on the screen through OR registration; make ONE state advance with the interact CLI only to reach the next screen, never to test behavior. |
| T-vet — after ALL screens captured | In parallel, Read the package's XAML authoring guide in full and the task guides it makes mandatory for the captured controls (both routed from the core guide § Documentation); the xaml/common-pitfalls.md sections matching the plan and the card entries it needs (on an existing project, first the Rule 22 reads greenfield T1 does); and, for each off-card activity, its Rule 21 doc plus get-default-xaml. |
| T-author | Complete Capture-First Fast Path scaffolding/authoring prerequisites; Write every screen's activities once (Rule 18). |
| T-gate | Run one sequential Bash chain/loop: attach the OR targets per the package's target-attachment guide && per-file relative---file-path validate over every edited file && build. |
| Debug cycle (consent-gated, uia-policies-catalog.md § Running UI Automation Workflows) | Run ONE Bash chain: window baseline && debug start && execution cancel && re-list windows. In the next turn, diff, reset the apps the run drove, and close stray windows via one interact-CLI Bash; a reset that raises a prompt the run never captured adds one snapshot-and-answer turn before the close. In the message that finishes cleanup, report with parallel context-file Writes, qualifying memory Writes, and SKILL.md § Completion Output as in greenfield T5. Read the verdict from the debug start envelope; never redirect it to a file and parse it in extra turns. |
Batch Object Repository definition updates, registration, and linking as sequential CLI loops/chains in one Bash call per phase, not one turn per entry. Split only when later calls need returned references or a file edit; keep screen-before-element linking and verify links in files. State advances and consent remain gates.
For coded mode, install needed packages and Write the empty [Workflow] stub (SKILL.md § Capture-First Fast Path step 2) BEFORE T0's window-baseline Bash. The first uip rpa command that loads the project snapshots coded partials from the packages and .cs files present at that moment; if the stub is missing then, authoring gets CS0246/CS0103. In T-vet, run ONE Bash per-file validate to regenerate .local/.codedworkflows/ObjectRepository.cs; Read it at the start of T-author, and author targets as Descriptors.*, never string names.
Default to author-once-after-capture; all OR refs are then in conversation. For long captures (5+ screens) with real context pressure, interleave per-screen authoring instead; run validate/build once at the end either way. For later screens in the same window, carry the prior OR screen reference into the next uia-configure-target invocation to skip OR-screen lookup; use the package's invocation guide routed from package-guide § Documentation. Keep indication fallback (physical user click) and every interact advance sequential, never batched or parallel. At debug-time selector failure, run the recover selector flow; never hand-edit selectors.
Open this reference as its own page
Execution Maps — what every turn-budgeted build journey shares
Read once per build, then the task's journey in execution-journeys-catalog.md (greenfield or brownfield XAML, greenfield or brownfield coded, UIA capture + build). Happy path, including the final report: greenfield ≤5 turns, brownfield ≤5; one repair cycle adds ≤2. Each T-row is one assistant message: all tool calls in one message cost one turn; one call per message costs N.
<!--skill-flavor:host-scope:start--> <!--skill-flavor:host-scope:end-->Tool vocabulary.
Edit= in-place replacement,Write= full-file write,Read/Glob/Grep= read/search,Bash= shell. Map these Claude Code names to the harness equivalents. If parallel calls are unavailable, preserve each grouping as consecutive calls; CLI chains still collapse round-trips.
If a harness rejects a batch for permissions, treat it as an approval gate, not a CLI failure; do not split it to evade approval. For Claude Code Bash calls, offer /uipath:install-permissions to install the curated allowlist with user approval; use the harness permission mechanism otherwise.
Source precedence — every activity you author
Use, in order:
- Card — common-activity-card.md, common-pattern-card.md
- Agent memory — validated prior-session snippet (see § Cross-session memory)
- Rule 21 triple —
activities find→<Activity>.mdread →get-default-xaml, fanned out inside T1/T2
validate + build gate all three. Card/memory hits skip discovery, never the gate.
Gate ≠ runtime proof
A clean validate + build does not prove runtime behavior. Silent failures that pass both include C# // in child/CDATA InvokeCode Code swallowing later code, WriteTextFile with explicit Encoding emitting a BOM, and stripped UIA N* Version failing only at runtime (xaml/common-pitfalls.md). For observable outputs (written files or entry-point out-arguments) with no external systems/UI, run exactly one uip rpa run --skip-build, then cat every output file; judge that chain in the report turn. Neither run nor output check gets another turn; the journey's gate and report rows (execution-journeys-catalog.md) place them.
Sequential gates — never batch across these
- Run
templates searchbeforeinit(Rule 2) only when the user names a template or domain pattern; use its result, including anAskUserQuestion, to choose--template-package-id. - Ask the Rule 2a framework/language question when the request has no signal.
- Ask the package version question (SKILL.md § Resolving Packages & Activity Docs, Step 1) before
packages install. On an existing project, ask it oncepackages versionshas returned, since it depends on the installed and available versions. On a greenfield project every needed package is absent: ask it in T1 beside theinitchain, naming the options (latest stable, latest prerelease), and take their numbers from that chain'spackages versionsoutput. - Keep every
AskUserQuestionand consent gate sequential. - Keep UIA state advances and indication sequential (see execution-journeys-catalog.md § Journey: UIA capture + build); capture screens require real application state.
Failure exits
| Symptom | Open |
|---|---|
validate structural/reference errors |
cli-reference.md § Validation Iteration Loop |
| XAML activity gotcha (property conflicts, scope) | xaml/common-pitfalls.md |
| Clean gate but wrong/empty runtime output | xaml/common-pitfalls.md silent-failure sections: § InvokeCode Code Property — Attribute Form Only, § WriteTextFile Emits a UTF-8 BOM, § UIA N* Activities Carry a Version |
Coded CS* errors |
coded/operations-guide.md § Common Issues and Fixes |
CLI timeout, EPIPE, 401, or not in the project folder |
cli-reference.md § CLI Error Recovery |
| Card snippet rejected by validate/build | Use the Rule 21 triple for that activity; report the stale entry via /uipath-feedback |
| UIA selector fails at debug time | Use the recover selector flow per uia-policies-catalog.md § Runtime Selector Failure Recovery; never hand-edit |
Cross-session memory
Use memory only when the harness provides persistent memory; otherwise skip silently.
Recall — T1 of every journey. Match entries by activity class + package major.minor. A hit skips that activity's Rule 21 triple; validate/build still gate.
Save — after a clean project build, in the report turn. Emit all qualifying saves as parallel Writes in the report message; never use a separate memory turn or one memory file per turn. A first-try clean gate on card-covered activities qualifies nothing. Save only:
- Validated XAML snippet for each off-card activity, keyed by activity class + package
major.minor+ date. - Error→root-cause→fix triples costing >1 validate attempt.
- Cross-version package gotchas.
Never save project facts (paths, asset names, connections; use project-context.md), UIA selectors/targets/OR references (per-app), UIA CLI syntax (package-owned/co-versioned), uip rpa flag shapes or run/debug payload fields (cli-reference.md owns them; report gaps via /uipath-feedback), or secrets. Process-level UIA lessons, such as a failure mode and fix direction, may be saved.
Expiry: if a recalled snippet fails validation, delete or overwrite it and fall back to the Rule 21 triple.
Open this reference as its own page
Authoring Integration Service ConnectorActivity XAML
End-to-end playbook for building a headlessly-runnable IS ConnectorActivity XAML from a known connector + operation. Use this whenever the request is "call connector X for operation Y from a XAML workflow" and Studio's designer is not available or not desired.
When to Use
- Headless / scripted authoring of IS workflows (no Studio GUI in the loop).
- CI-style generation where the XAML must be portable across machines.
- Any time you know the connector key and operation name upfront (e.g.,
uipath-salesforce-slack+send_message_to_channel_v2).
Prefer this over per-product BAF activity packages (UiPath.Slack.Activities, etc.). Those wrap IS internally and use a more complex BAF (Business Activity Framework) XAML shape that is equally fragile to hand-author. The IS ConnectorActivity flow below is schema-driven and mechanical.
Connector Discovery Commands
Explore the connector before writing XAML (requires uip login — see Prereq below):
uip is connectors list --output json # connector keys available to the tenant
uip is activities list <connector-key> --output json # activity names + method + operation
uip is resources list <connector-key> --output json # data objects/resources exposed
uip is resources describe <connector-key> <object-name> --operation Create --output json # field schema
resources describe is the authoritative field schema — full usage in Step 5.
Activity Shape
<isactr:ConnectorActivity
Configuration="<base64-gzip-blob>"
ConnectionId="<CONNECTION_GUID>"
UiPathActivityTypeId="<ACTIVITY_TYPE_GUID>"
xmlns:isactr="http://schemas.uipath.com/workflow/integration-service-activities/isactr">
<isactr:ConnectorActivity.FieldObjects>
<isactr:FieldObject Name="<fieldName>" Type="FieldArgument">
<isactr:FieldObject.Value>
<InArgument x:TypeArguments="x:String">
<CSharpValue x:TypeArguments="x:String">"<literal>"</CSharpValue>
</InArgument>
</isactr:FieldObject.Value>
</isactr:FieldObject>
<!-- repeat per field; include every field from the default XAML even if unset -->
</isactr:ConnectorActivity.FieldObjects>
</isactr:ConnectorActivity>
Three ingredients:
UiPathActivityTypeId— the operation's type GUID (fromactivities find).ConnectionId— the IS connection's GUID (fromuip is connections list).Configuration— an opaque base64 + gzip JSON blob encoding connector/operation identity. Never hand-edit. Always take the value fromactivities get-default-xaml.
IS activity types & how fields resolve
get-default-xaml produces all four IS activity shapes from a typeId (+ a live connection). What unlocks an activity's fields differs by type — hand the tool the right selector and it returns the resolved FieldObjects:
| Activity | What it is | How to resolve its fields |
|---|---|---|
ConnectorActivity |
A connector operation (create / get / update …) | typeId + connection. A generic operation needs --object-name <obj> (the record type); criteria fields fed back via --field-values expand the rest (Step 4). |
ConnectorTriggerActivity |
Fires when a connector event occurs | Curated triggers resolve from typeId + connection; a generic trigger needs --object-name <obj> (the object whose changes it watches). |
ConnectorPersistenceActivity |
Suspends the workflow until a connector event | Discover events with uip is activities list <connector> --triggers, then --event-operation <op> resolves the event's fields. A named event auto-resolves its single object; a generic/multi-object event also needs --object-name <obj> (Step 4). |
ConnectorHttpActivity |
Generic HTTP-request escape hatch | Standard request fields (method, url, headers, query, body) — author them directly; they are the same for every connector. |
Same principle throughout: pass the selector the activity needs, get back its resolved schema. A bare call (no selector) returns the correctly-typed activity with its baseline fields.
Step-by-Step Flow
Prereq: uip login
uip is * commands silently fail without an authenticated session. Log in first:
uip login # production (cloud.uipath.com)
uip login --authority "<AUTHORITY_URL>" # non-default host (Automation Suite, dedicated)
The command is interactive (opens a browser). If you need the user to run it themselves, ask them to type ! uip login so the token lands in the current session.
Step 1 — Install UiPath.IntegrationService.Activities
Required for the isactr:ConnectorActivity type.
uip rpa packages versions --package-id UiPath.IntegrationService.Activities --project-dir "<PROJECT_DIR>" --output json
uip rpa packages install --packages id=UiPath.IntegrationService.Activities --project-dir "<PROJECT_DIR>" --output json
Step 2 — Find the operation's activityTypeId
uip rpa activities find --query "<search terms>" --project-dir "<PROJECT_DIR>" --output json
In each result, look for:
activityTypeId→ populated only for IS/dynamic activities. Copy this value.description→ identifies which operation (e.g."Send messages to public or private Slack channels."vs"Send a reply to a message in a Slack channel.").
If activityTypeId is empty, the activity is a non-dynamic BAF/vendor activity (e.g. UiPath.Slack.Activities.Messages.SendMessage) — different flow, not covered here.
activities find is not exhaustive — be ready to iterate. Results vary by connector: some expose 6+ typed operations with rich descriptions (Slack); others expose only 1-2 (Outlook). Try several query phrasings ("send email", "<connector> send", the literal operation name from uip is activities list). If no typeId surfaces:
- The operation may only be reachable via the generic
ConnectorHttpActivitytypeId (suffix...httpRequest...). Use it as a fallback — see Typed Operation vs Generic HTTP for its standard, connector-independent request fields. - Different connectors that share a schema (e.g. a mock connector + its real counterpart) often share typeIds. The same
fbdeec58-..."Send Email" typeId works for bothuipath-mock-outlookanduipath-microsoft-outlook365— theConnectionIdat runtime determines which backend receives the call. Don't be surprised if the discovered typeId's description mentions a different connector than the one you're targeting.
Step 3 — Get the connection ID
uip is connectors list --output json # find connector key
uip is connections list <connector-key> --output json # list tenant's connections
If none exist: uip is connections create <connector-key> (interactive OAuth). If that can't be done in-session, use a placeholder 00000000-0000-0000-0000-000000000000 and flag it for the user — but the workflow will fail at runtime until a real connection is wired up.
Verify a connection is active: uip is connections ping <connection-id>. If the ping fails, offer to re-authenticate with uip is connections edit <connection-id> (re-runs the OAuth flow for expired/revoked connections).
Step 4 — Get the fully-populated default XAML
This is the unlock step. With both the type ID and connection ID:
uip rpa activities get-default-xaml \
--activity-type-id "<TYPE_ID>" \
--connection-id "<CONNECTION_ID>" \
--project-dir "<PROJECT_DIR>" \
--output json
The response contains the complete ConnectorActivity element with:
- A real
Configurationblob for that specific connector+operation combo. - A
FieldObjectslist with one entry per field of the operation's resolved schema (older CLI versions emit only the curated/visible-by-default subset). - A real
ConnectionId(uses the supplied one, or auto-resolves a tenant default).
Without --activity-type-id, the default comes back essentially empty (Configuration={x:Null}, no fields). That generic default is not runnable.
Pass field values with --field-values
get-default-xaml accepts literal input-field values as repeatable key=value pairs (one --field-values per field). Two effects:
- Values are pre-bound as literals in the returned
FieldObjects— no hand-editing ofInArgument/CSharpValuefor literal values (expressions still go through Step 6). - Schema expansion. Many operations expose only a few "criteria" fields by default and reveal the rest of the schema only once those criteria have values. In Studio's designer the re-resolve fires when the user commits a criteria field in the canvas; headlessly, passing the criteria via
--field-valuestriggers the same re-resolve, and theConfigurationblob comes back with the expanded field set as newFieldObjects.
Run it twice — discover, then expand. You won't know a connector's criteria fields ahead of time, so make two calls:
- First call — no
--field-values. WhateverFieldObjectscome back are the operation's prerequisite fields. Those returned field names are your criteria candidates — there is no separate place to look them up; the curated baseline is the list. - Second call — feed those same field names back inline with
--field-values. The response now carries the expanded schema; author against it.
# 1. discover the criteria fields (curated baseline)
uip rpa activities get-default-xaml --activity-type-id "<TYPE_ID>" --connection-id "<CONN>" --project-dir "<P>" --output json
# 2. feed those field names back inline to expand the rest
uip rpa activities get-default-xaml --activity-type-id "<TYPE_ID>" --connection-id "<CONN>" \
--field-values <fieldFromStep1>=<value> --project-dir "<P>" --output json
When you already know valid criteria values up front, the second call alone does both.
Expansion requires a LIVE connection and real values — there is no offline path. It is a design-time cloud round-trip to the connector.
--connection-idmust be an enabled connection that resolves on your currentuip login(correct org + tenant), and each value must actually exist in that system. If the connection is dead / wrong-tenant, or a value is invalid, the call returns the curated baseline unchanged, with no error and no new fields — a silent no-op, not a visible failure. So when expansion "does nothing", suspect the connection or the values, never the flag; re-confirm the connection is live (Step 3) before concluding the activity has no more fields.
Field-name encoding. Pass names exactly as they appear in the returned FieldObjects — copy them verbatim from the previous call's output. Don't hand-encode or invent names: the connector's encoding (nested paths, arrays — see § FieldObject Name Encoding Rules) is already applied in what it hands you. An unknown name fails fast with the list of available fields, so use that error as discovery rather than guessing.
Older CLI fallback: if --field-values is not recognized, upgrade uip. Until then the expansion is not reachable headlessly — bind only fields present in the returned XAML and treat missing ones per § Hidden Secondary Fields.
Resolve persistence event fields with --event-operation
A ConnectorPersistenceActivity ("suspend until an event") exposes no event fields until an event operation is chosen — the headless equivalent of picking the event in the designer before its fields appear. The event operation is a connector-specific value (e.g. TICKET_UPDATED, never the prose "ticket updated"), so discover it — do not guess it.
Step A — list the connector's events (the same catalog the designer's dropdown uses; no connection needed):
uip is activities list <connector-key> --triggers --output json
Each entry's Name is the value for --event-operation; its ObjectName tells you the kind:
Name DisplayName ObjectName IsCurated
TICKET_UPDATED Ticket Updated tickets Yes ← named event: object is built in
CREATED Record Created N/A No ← generic op: choose an object too
- Named event (
ObjectNamepopulated, e.g.TICKET_UPDATED) — pass itsNameto--event-operation; its single object auto-resolves, so no--object-nameis needed. - Generic op (
CREATED/UPDATED/DELETED,ObjectNameisN/A) — also pass--object-name <obj>. List the objects it applies to with:uip is triggers objects <connector-key> CREATED --output json
Step B — resolve the activity with the chosen operation:
uip rpa activities get-default-xaml --activity-type-id "<TYPE_ID>" --connection-id "<CONN>" \
--event-operation "TICKET_UPDATED" --project-dir "<P>" --output json
The returned Configuration carries the resolved event fields as FieldObjects. Without --event-operation you get the bare activity (correct default, no event fields). It is the persistence analogue of --field-values criteria — a selector that unlocks the schema — and the resolution needs a live connection (same cloud round-trip and silent-no-op caveat as above). Combine with --field-values to also pre-bind values.
Select the object for generic activities with --object-name
A generic ConnectorActivity (Insert / Get / Delete a record) or a generic event has no object baked into its typeId, so get-default-xaml returns it bare until you name the object — the headless equivalent of the designer's object dropdown. Pass --object-name <obj>:
uip rpa activities get-default-xaml --activity-type-id "<TYPE_ID>" --connection-id "<CONN>" \
--object-name issue --project-dir "<P>" --output json
Discover valid object names (use the Name field, not the display name):
- Generic activity →
uip is resources list <connector-key> --output json - Generic event →
uip is triggers objects <connector-key> <EVENT> --output json
A named event auto-resolves its single object, so --object-name is only needed for generic operations and multi-object events. It is the same kind of selector as --event-operation (identity that unlocks the schema), needs a live connection, and combines with --event-operation and --field-values.
Step 5 — Read the operation's field schema
For each field you want to bind, you need its declared name and dataType. Read the schema from Integration Service:
uip is resources describe <connector-key> <object-name> --operation Create --output json
The second positional is the object/resource name (from uip is resources list), not the operation; the operation goes in --operation. Note: it's resources describe (not activities describe). activities only has list.
The response includes a metadataFile path like:
~/.uipath/cache/integrationservice/<connector>/_static/<operation>.Create.json
Read that file directly for the full schema — parameters, requestFields, responseFields, each with name, dataType, required, description, and any enum values. Never guess field names from memory — the schema is the source of truth, and guessed names trigger a Configuration contains a breaking change runtime error.
Step 6 — Bind values using InArgument + CSharpValue
Only needed for expression values or when editing an existing XAML — literal values are better passed via --field-values in Step 4, which pre-binds them in the returned XAML.
For each field you want populated:
<isactr:FieldObject Name="<fieldName>" Type="FieldArgument">
<isactr:FieldObject.Value>
<InArgument x:TypeArguments="x:String">
<CSharpValue x:TypeArguments="x:String">"<literal or expression>"</CSharpValue>
</InArgument>
</isactr:FieldObject.Value>
</isactr:FieldObject>
Leave the rest as bare <isactr:FieldObject Name="..." Type="FieldArgument" /> entries — keep every FieldObject from the default XAML, even if you don't bind a value. Removing fields causes schema-mismatch errors.
Do not put literal values in the FieldObject Value="" attribute — Studio silently ignores that path. Use the element form above.
For VB projects, swap CSharpValue → [bracket] expression shorthand on the InArgument element per the project's expression language (see xaml/xaml-basics-and-rules.md).
FieldObject Name Encoding Rules
Schema field names from describe / the cached JSON (message.toRecipients, send-mail-v2, etc.) must be translated when written as FieldObject Name:
| Schema character | XAML encoding | Example |
|---|---|---|
. (dot) |
_sub_ |
message.body.content → message_sub_body_sub_content |
- (hyphen) |
minus_sign |
send-mail (in Jit_send-mail) → Jit_sendminus_signmail |
_ (underscore) |
unchanged | send_as → send_as |
[*] (array suffix) |
_array |
tags[*] → tags_array, fields[*].id → fields_array_sub_id |
Apply rules in order; translate every segment for nested paths (collaborator_ids[*] → collaborator_ids_array).
Default XAML reflects correct encoded names for fields it returns — copy verbatim. With current CLI versions the returned FieldObjects cover the blob schema exhaustively; a schema-documented field that is still absent is criteria-gated or a query parameter — see Hidden Secondary Fields.
Matching x:TypeArguments to the Field's Data Type
The schema's type (or dataType) determines the x:TypeArguments on both the InArgument and the inner CSharpValue:
| Schema type | XAML | Value literal |
|---|---|---|
string |
x:String |
"hello" |
boolean |
x:Boolean |
true / false (no quotes) |
integer / int32 |
x:Int32 |
42 |
number / double |
x:Double |
3.14 |
date-time |
s:DateTime (plus xmlns:s="clr-namespace:System;assembly=System.Private.CoreLib") |
DateTime.UtcNow |
| enum | x:String with allowed value |
"high" |
| object / array | x:String with JSON-encoded content |
"{\"key\":\"value\"}" |
Mismatched types (e.g., binding saveToSentItems with x:String when the field is boolean) cause a Configuration contains a breaking change error at runtime.
Example — boolean field:
<isactr:FieldObject Name="saveToSentItems" Type="FieldArgument">
<isactr:FieldObject.Value>
<InArgument x:TypeArguments="x:Boolean">
<CSharpValue x:TypeArguments="x:Boolean">true</CSharpValue>
</InArgument>
</isactr:FieldObject.Value>
</isactr:FieldObject>
Hidden Secondary Fields
A field is only honored at runtime if it exists in the Configuration blob's schema — the blob, not the FieldObjects list, is the contract. A hand-added FieldObject whose field is missing from the blob's schema passes validate and build clean and is silently dropped by the connector at runtime — the API call goes out without it, typically surfacing later as a confusing connector/runtime error (a 4xx about missing or invalid fields) far from the XAML that caused it.
When a schema-documented field is absent from the returned FieldObjects:
- Criteria-gated field (most common — body/custom fields revealed by prerequisite values): re-run
get-default-xamlwith--field-values <criteria>=<value> ...(Step 4) and author against the returned XAML — its blob carries the expanded schema and the field now has aFieldObject. Do not graft the field into the previous XAML; the old blob does not know it. - Query parameter: check the schema's
queryParameters— those never appear asFieldObjectsand have no per-field XAML override (see Gotchas). - Older CLI without
--field-values: the expansion is not reachable headlessly. Have a developer commit the criteria fields once in Studio's designer and copy the resultingConfiguration+FieldObjects, or upgradeuip.
The name-encoding rules above apply to expanded fields too — reference them by the encoded name exactly as the expanded XAML returns it, both in --field-values and when binding expression values in Step 6.
Step 7 — Validate and run
uip rpa validate --file-path "<your-workflow>.xaml" --project-dir "<PROJECT_DIR>" --output json
uip rpa run --file-path "<your-workflow>.xaml" --project-dir "<PROJECT_DIR>" --output json
If HasErrors: true, the ErrorMessage field carries the compile/runtime error.
ConnectorActivity Editing Rules
What you may and may not touch on an existing ConnectorActivity:
| Property | Editable? | Description |
|---|---|---|
Configuration |
NEVER | Opaque blob (see Activity Shape above). Obtained only from activities get-default-xaml. |
ConnectionId |
Yes (replace GUID) | Swap to a different connection of the same connector type (uip is connections list). |
UiPathActivityTypeId |
NEVER | Identifies the connector operation. |
DisplayName |
Yes | Human-readable designer name. |
In FieldObjects you CAN: change input field values inside FieldObject.Value (literal or <CSharpValue> variable binding).
You CANNOT: change field Name or Type values (schema-defined), alter output field structure (JIT-typed), or add/remove FieldObject entries (the set comes from get-default-xaml — see § Hidden Secondary Fields for the expansion path).
JIT-generated assembly names on output types are unpredictable and connection-specific:
CDF573A04A6_search_r.VeKd1XI2qK1X56UO2Br3Ui3
^connection(last10) ^operation ^content hash
They are derived from SHA-512 hashes of the type schema and generated by the runtime — the corresponding namespace imports and assembly references MUST come from activities get-default-xaml output. Never construct them.
Operation output is strongly typed
The operation's result is exposed as an output FieldObject named Jit_<operation>, typed to a generated record type for that object — so downstream expressions that read its members (record.id, records.First().name) compile, and uip rpa build binds the consuming variable to the right type.
That typed shape is generated from the live connection's schema while get-default-xaml resolves the activity; there is no flag for it — typing is automatic when resolution succeeds against a connection. If it cannot be generated — no usable connection at resolve time, or a connector schema that won't compile — the output degrades to System.Object: the activity stays valid, but typed member access no longer compiles. Re-resolve with a valid, enabled connection; treat a System.Object output as the signal that typing was skipped.
Typed Operation vs Generic HTTP
Every connector exposes a ConnectorHttpActivity with a typeId suffixed like ...httpRequest... — a generic escape hatch for arbitrary HTTP calls. Prefer a typed operation (e.g. send_message_to_channel_v2) whenever one exists: it encodes the endpoint, method, and field schema for you. Only fall back to the HTTP activity when the connector lacks a modeled operation for what you need.
get-default-xaml for an HTTP typeId returns a correctly-typed ConnectorHttpActivity with a valid Configuration. Its fields are the standard HTTP request fields — method, url, headers, query, body (inputs), plus out_body / out_headers / out_code (outputs) — identical across connectors, so author the ones you need directly per Step 6 instead of reading a per-operation schema. The ConnectionId still scopes the call at runtime.
Worked Example: Slack "Send Message to Channel"
End-to-end skeleton. Assumes uip login done and UiPath.IntegrationService.Activities installed.
# 1. Discover typeId
uip rpa activities find --query "Send Message to Channel" --project-dir "$P" --output json
# → 37a305b2-89b1-315d-b73f-1778839a6c47
# 2. Find connection
uip is connections list uipath-salesforce-slack --output json
# → c57d4fd4-9dc1-46f8-8add-a835283077fa
# 3. Get default XAML (returns Configuration blob + FieldObjects)
uip rpa activities get-default-xaml \
--activity-type-id "37a305b2-89b1-315d-b73f-1778839a6c47" \
--connection-id "c57d4fd4-9dc1-46f8-8add-a835283077fa" \
--project-dir "$P" --output json
# 4. Read the schema to know which fields are required
uip is resources describe uipath-salesforce-slack send_message_to_channel_v2 --operation Create --output json
cat ~/.uipath/cache/integrationservice/uipath-salesforce-slack/_static/send_message_to_channel_v2.Create.json
# → `send_as` is required (default "bot"); `channel` + `messageToSend` are the relevant optional fields
Resulting ConnectorActivity body (truncated — preserve the full FieldObject list from the default):
<isactr:ConnectorActivity
Configuration="H4sIAAAAAAAACu1a624b..."
ConnectionId="c57d4fd4-9dc1-46f8-8add-a835283077fa"
UiPathActivityTypeId="37a305b2-89b1-315d-b73f-1778839a6c47"
xmlns:isactr="http://schemas.uipath.com/workflow/integration-service-activities/isactr">
<isactr:ConnectorActivity.FieldObjects>
<isactr:FieldObject Name="channel" Type="FieldArgument">
<isactr:FieldObject.Value>
<InArgument x:TypeArguments="x:String">
<CSharpValue x:TypeArguments="x:String">"C09UZSPDANP"</CSharpValue>
</InArgument>
</isactr:FieldObject.Value>
</isactr:FieldObject>
<isactr:FieldObject Name="messageToSend" Type="FieldArgument">
<isactr:FieldObject.Value>
<InArgument x:TypeArguments="x:String">
<CSharpValue x:TypeArguments="x:String">"hello"</CSharpValue>
</InArgument>
</isactr:FieldObject.Value>
</isactr:FieldObject>
<isactr:FieldObject Name="send_as" Type="FieldArgument">
<isactr:FieldObject.Value>
<InArgument x:TypeArguments="x:String">
<CSharpValue x:TypeArguments="x:String">"bot"</CSharpValue>
</InArgument>
</isactr:FieldObject.Value>
</isactr:FieldObject>
<!-- keep all remaining FieldObject entries from the default as bare Name/Type pairs -->
</isactr:ConnectorActivity.FieldObjects>
</isactr:ConnectorActivity>
Worked Example: criteria-gated expansion
Some "edit/update record" operations surface only their prerequisite fields by default (e.g. a record's project + type + key) and reveal the full body schema only once those criteria have values — the headless equivalent of committing those fields in the designer canvas:
# Criteria values trigger the schema expansion AND get pre-bound as literals in one call.
uip rpa activities get-default-xaml \
--activity-type-id "<TYPE_ID>" \
--connection-id "<LIVE_CONNECTION_ID>" \
--field-values <criteria1>=<value> --field-values <criteria2>=<value> \
--project-dir "$P" --output json
The returned Configuration blob now carries the expanded schema, and the previously hidden body/custom fields appear in FieldObjects. Bind remaining values there directly in the same call (literal) or via Step 6 (expression). Authoring one of those expanded fields against the unexpanded blob is the silent-drop failure in § Hidden Secondary Fields. Needs a live connection and valid criteria values — see the silent-no-op note in Step 4.
Gotchas
JIT OutArgument corruption — When Studio's designer modifies an IS XAML, it can inject a JIT-typed
OutArgumentinto theJit_<operation>FieldObject that references a dynamically-compiled Studio-session-local assembly:<isactr:FieldObject Name="Jit_send_message_to_channel_v2" Type="FieldArgument"> <isactr:FieldObject.Value> <OutArgument x:TypeArguments="uiascb:send_message_to_channel_v2_Create" /> </isactr:FieldObject.Value> </isactr:FieldObject>On any fresh load (new Studio session, Helm, CI) that assembly doesn't exist and compile fails with
Unable to create activity builder ... Cannot create unknown type '{...}OutArgument({...}<op>_Create)'. Strip the injected OutArgument back to bare form before shipping or running headlessly:<isactr:FieldObject Name="Jit_send_message_to_channel_v2" Type="FieldArgument" />Also remove the
xmlns:uiascbnamespace declaration from the root<Activity>element if nothing else references it. Tracked as PILOT-4812.Connector-backend errors surface at runtime, not validation — Things like
channel_not_found,not_authed, rate-limit failures etc. are returned by the connector's backend after the activity calls out. They appear in theErrorMessageof an actual run (withHasErrors: true) or in streamed log entries from the workflow's own logging, never fromvalidate. Validation can only tell you the XAML is structurally correct and the connection slot is filled — not that the target entity exists or that the bot has permission.Configuration blob's
ConnectorKeymay be a mock/template — it is not routing metadata — Decompressing the Configuration blob can reveal"ConnectorKey": "uipath-mock-<something>"even when you're targeting the real production connector (e.g.uipath-microsoft-outlook365). The typeId encodes the operation schema; theConnectionIdattribute determines which backend actually gets called at runtime. Don't try to "correct" the blob — it's baked, and any edit invalidates it (Configuration contains a breaking change). A mismatch betweenConnectorKeyin the blob and the connection's connector is expected for connectors that share schemas (mocks, legacy vs. v2, etc.) and is not an error.Query parameters vs request fields — Some operation params (e.g. Outlook's
saveAsDraft) live in the schema'squeryParametersblock, notrequestFields, and do not appear asFieldObjectentries in the default XAML. Their defaults come from the Configuration blob and are applied server-side. There is no per-field XAML override for query parameters — if the default doesn't match your need, either use a different typeId (e.g. a v2 variant), or switch the connector. Always check the schema'squeryParametersarray for hidden-by-default toggles before running.Primary vs Secondary field designation — Decompressing the Configuration blob exposes an
InputFieldslist where each entry has a"Design": { "Position": "Primary" | "Secondary" }. Primary fields are what the connector considers "must-bind for the call to be meaningful" (e.g.To,Subject,Bodyfor Send Email). Useful discovery hint when the schema marks most fields asrequired: falsebut the call actually requires several to be bound to succeed.
Anti-Patterns
- Do not guess
FieldObject Namevalues. Read the schema JSON from~/.uipath/cache/integrationservice/<connector>/_static/<operation>.Create.json. - Do not hand-edit the
Configurationblob. It's base64 + gzip of an internal serialization — any edit triggers abreaking changeruntime rejection. - Do not use
activities get-default-xamlwithout--activity-type-idfor IS activities — the generic default is empty and unusable. - Do not drop FieldObjects from the default. The full list is part of the schema contract.
- Do not hand-add a
FieldObjectfor a field absent from the returned XAML — it validates clean and is silently dropped at runtime. Re-runget-default-xamlwith--field-valuesto expand the schema instead (§ Hidden Secondary Fields). - Do not put values in the
FieldObject Value=""attribute — use<FieldObject.Value><InArgument><CSharpValue>elements.
Related References
- xaml/xaml-basics-and-rules.md § Step 1.9 — where this flow slots into the overall XAML phase structure.
- xaml/common-pitfalls.md § Connection Service Pattern —
ConnectionIdrequirements for BAF-scope activities (O365/GSuite).
Open this reference as its own page
Library Authoring Guide
How to produce a reusable library: a NuGet package whose public workflows surface as activities in every consuming project's panel. For finding and consuming libraries that already exist, see tenant-library-search-guide.md.
When to Build a Library
Good fit:
- Complex reusable actions shared by multiple processes — login flows, paginate-and-extract, shared validators, notification senders
- Standard practices the organization wants enforced once — logging wrappers, error handlers
- Interactions with a shared corporate system (ERP, CRM) that many automations touch
Not a fit:
- Process-specific logic — used once, belongs in the project
- Unstable code — frequent changes create versioning overhead for every consumer
- Tightly coupled workflows — only make sense inside one process
- Single activities — wrapping one
Clickas a library activity adds no value. Extract macro-actions (DownloadInvoices), not micro-primitives
Boundaries:
| Need | Go to |
|---|---|
| Start new projects from a standard baseline | Project templates — environment-setup.md § Template Selection |
| Share UI selectors across projects | UI Libraries — uia-policies-catalog.md § Object Repository as a Published UI Library |
| Reuse logic inside one project | Separate workflow file — environment-setup.md § Designing for Reuse |
Creating and Structuring
uip rpa init \
--name "<LIBRARY_NAME>" \
--location "<PARENT_DIR>" \
--template-id "LibraryProcessTemplate" \
--expression-language <VisualBasic|CSharp> \
--target-framework <Windows|Portable> \
--description "<DESCRIPTION>" \
--output json
<LIBRARY_NAME>: descriptive and scoped, dotted segments accepted —Company.Email.Utilities, notHelpers. The name becomes the package ID.- Default
--target-framework Portable(Cross-platform) for libraries. Cross-platform libraries (packed tolib/net8.0) install into both Cross-platform and Windows consumer projects; Windows libraries (lib/net8.0-windows7.0) install only into Windows projects. Choose Windows only when the library needs Windows-only activities or dependencies — every Windows-only pick shrinks the consumer base. <DESCRIPTION>(project.json→description) becomes the package description shown in the feed — write it for consumers.- The template scaffolds
NewActivity.xaml; replace it — delete the file and pointproject.json→mainat a real workflow, then add one workflow file per activity. - Library
project.jsondiffers from a process:designOptions.outputTypeis"Library", and there is noentryPoints(SKILL.md Rule 15) — do not add one.
Public vs private workflows
Every workflow file is public by default — packed as an activity. To keep a helper internal, add its filename to project.json:
"designOptions": {
"libraryOptions": {
"privateWorkflows": [
"ValidateEmailFormat.xaml"
]
}
}
Private workflows compile into the package and stay invocable from the library's own workflows, but no activity is generated for consumers.
Activity identity
- Activity name and class = workflow file name (
SendInvoiceNotification.xaml→ activitySendInvoiceNotification); a coded workflow's = its class name plusActivity(classCopyFolder→ activityCopyFolderActivity), its properties named as coded/operations-guide.md § Add a Workflow File states - Argument defaults reach consumers: a XAML workflow's root-element default (xaml/xaml-editing-catalog.md § Setting Default Values for Arguments) and a coded workflow's parameter default compile into the package and apply when a consumer leaves the argument unset.
packages inspectprints no defaults, so each argument's description states its default - Activity namespace = library name with dots and hyphens sanitized to underscores (
Company.Email.Utilities→ namespaceCompany_Email_Utilities); the package ID and assembly keep the dotted name. Read the real namespace fromuip rpa packages inspecton the packed.nupkg— never derive it - Property tooltip = the argument's description annotation in XAML:
sap2010:Annotation.AnnotationTexton thex:Property
Activity Layout — the sidecar file
Each public workflow can ship as a rich activity: custom display name, tooltip, color, SVG icon, and per-property display names, placeholders, input widgets, required flags, and category grouping. All of it is authored in a sidecar JSON next to the workflow — <WORKFLOW_NAME>.xaml.json:
{
"DisplayName": "Send Invoice Notification",
"Tooltip": "Sends an invoice notification email and returns a delivery summary",
"Color": "#1F8FFF",
"OriginalIconFileName": "SendInvoiceNotification.xaml.svg",
"Arguments": [
{
"Name": "in_RecipientEmail",
"DisplayName": "Recipient email",
"Category": "Input",
"Tooltip": "Email address that receives the notification",
"Placeholder": "someone@company.com",
"Widget": "TextComposer",
"IsRequired": true,
"IsPrincipal": true,
"ArgumentType": 0
},
{
"Name": "in_UrgentDelivery",
"DisplayName": "Urgent delivery",
"Category": "Options",
"Tooltip": "Send with high priority",
"Widget": "Toggle",
"IsRequired": false,
"IsPrincipal": false,
"ArgumentType": 0
}
]
}
Rules:
Arguments[].Namemust match the XAML argument name exactly — the sidecar decorates arguments, it does not declare them.- The sidecar wins over XAML annotations. Without a sidecar, the argument annotation is the tooltip and the file name is the display name; the sidecar overrides both and adds everything else.
- Icon: place an SVG next to the workflow as
<WORKFLOW_NAME>.xaml.svgand reference it inOriginalIconFileName.packembeds it as a package resource. Widgetis the property's input type (Studio: "Input type"). Valid values depend on the argument's type — omitWidgetfor the type's default editor:
| Argument type | Widget values |
|---|---|
String |
TextComposer (default), RichTextComposer, Dropdown, AutocompleteForExpression, RadioGroup |
Boolean / bool? |
Toggle (default), ConditionBuilder, NullableBoolean |
| Numeric | Number (default), Dropdown |
DateTime |
Datetime |
TimeSpan |
Timespan |
String[] |
StringArray |
Dictionary |
Dictionary |
DataSourceItems (string array of choices) applies only to Dropdown, RadioGroup, and AutocompleteForExpression.
5. Category groups properties in the activity's body, in sidecar argument order; IsPrincipal: true surfaces the property on the activity card, IsRequired: true marks it mandatory.
6. HelpLink is a valid sidecar field but stays design-time only — it does not ship in the compiled activity metadata.
7. ArgumentType is 0 for plain arguments.
pack compiles the sidecar into the activity metadata embedded in the library assembly — consumers see the layout in their Activities panel with no extra steps.
The Public-Workflow Contract — MANDATORY
Each public workflow is an API surface. Apply every rule:
- Name workflows verb-noun PascalCase, no spaces —
SendNotificationEmail.xaml,DownloadInvoices.xaml. The file name becomes the activity name in the consumer's panel. - Public arguments follow the Workflow Analyzer naming rules in force, as every workflow argument does (SKILL.md Common Rule 4c): PascalCase after whatever prefixes those rules require. Argument names become activity property names, which consumers' XAML attributes and coded calls use as written; give each public argument a display name in the layout sidecar (§ Activity Layout) and the property grid shows readable labels.
- Describe every public argument via its
sap2010:Annotation.AnnotationText— descriptions ship as property tooltips. For display names, placeholders, widgets, and grouping, add the layout sidecar (§ Activity Layout). - Leave no analyzer naming warning.
build/packreport each argument whose name breaks a naming rule in force (Argument <Name> does not respect the set pattern …,doesn't have datatable prefix); rename it before packing. A published library's existing public arguments keep their names and their warnings: renaming one is a breaking change (§ Versioning), and the compatible change, a new argument beside the old, follows the rules. - Return application handles. A workflow that opens or attaches to an app outputs the window/browser object, its card's Close set to
Neverso the window outlives the call; downstream public workflows accept it as an input argument instead of reopening, and the workflow that ends the application's work closes it with CloseAlwayson its card. - Post-authoring audit: before packing, re-check every public workflow against rules 1-3 — name form, argument naming, argument descriptions.
Error Contract
- Throw meaningful exceptions —
BusinessRuleExceptionfor input validation failures, with the offending value in the message. Let system exceptions propagate to the consumer. - Never swallow errors: no empty
Catchblocks, nooutboolean success flags in place of exceptions. A swallowed error returns control to a consumer whose target app is in an unknown state. - Never set
ContinueOnErrorinside a library — the consumer decides failure policy. - No hardcoded paths — accept paths as arguments, or build from
UiPath.Constants.Project.Locationfor files packed with the library. - No embedded config or secrets — read Orchestrator assets at the consumer level and pass them in as arguments; a credential by its asset's name (SKILL.md Common Rule 5a).
Versioning
projectVersion in project.json is the package version (override at pack time with --package-version). Follow SemVer:
| Bump | When | Consumer impact |
|---|---|---|
Patch x.x.1 |
Bug fix, no interface change | Safe drop-in |
Minor x.1.x |
New workflow or new optional argument, backward compatible | Safe upgrade |
Major 1.x.x |
Renamed/removed workflow or argument, changed behavior | Code changes required |
- Renaming a public workflow or argument is a breaking change — major bump. To change an argument compatibly, add a new one and keep the old.
- Never delete published versions from the feed — consumers pin them.
libraries deleteis for mistaken uploads only. - Consumers pin exact versions in production.
Pack & Publish
uip rpa pack "<PROJECT_DIR>" "<OUTPUT_DIR>" --output json
uip rpa publish "<OUTPUT_DIR>/<LIBRARY_NAME>.<VERSION>.nupkg" --output json
publishreads the package's type and sends a library to the tenant Libraries feed (Data.Feed:Orchestrator Tenant Libraries Feed), not the processes feed a process goes to. Other destinations, refusals and the duplicate-version error: cli-reference.md § Pack & Publish to Orchestrator.<OUTPUT_DIR>must be OUTSIDE the project directory tree —packrefuses an output path inside the project. Use a sibling directory (e.g.dist/).- Verify the publish:
uip or libraries list --search "<LIBRARY_NAME>" --output json
Returns the library with Key = <PackageId>:<Version> and ProjectType: "ProcessLibrary".
Consumption Loop
- Discover existing libraries before building new ones — tenant-library-search-guide.md (SKILL.md Rule 9).
- Install into the consumer as a dependency — SKILL.md § Resolving Packages & Activity Docs. The install records the dependency in the consumer's
project.json; the library's activities become available. - Build-time resolution: signed in,
buildandpackrestore the library from the tenant's libraries feeds, as the install does; no extra NuGet source is needed. - Author against the library in consumer XAML. Once the library is installed,
activities findreturns its public workflows andactivities get-default-xamlreturns each one's element with its arguments as properties, without their types or directions — read those from the package itself:
uip or libraries download "<PackageId>:<Version>" --destination "<LOCAL_DIR>/<LIBRARY_NAME>.<VERSION>.nupkg" --output json
uip rpa packages inspect --nupkg-path "<LOCAL_DIR>/<LIBRARY_NAME>.<VERSION>.nupkg" --output json
Declare the namespace and use each public workflow as an element — property names = the library's argument names:
<Activity ... xmlns:lib="clr-namespace:<SANITIZED_NAMESPACE>;assembly=<LIBRARY_NAME>">
<lib:SendInvoiceNotification in_RecipientEmail="..." in_InvoiceId="..." />
<SANITIZED_NAMESPACE> is the underscore form from § Activity identity. Bind non-literal properties per the project's expression language rules (xaml/xaml-basics-and-rules.md).
- Stale design session after the dependency becomes resolvable:
buildcompiles the consumer butvalidatekeeps failing withCannot create unknown typefor the library activity. Runuip rpa project close --project-dir "<CONSUMER_PROJECT_DIR>"and re-runvalidate; the next command reloads the project. - Same version repacked: the package cache keeps the first package under an id and version and ignores a repack, so bump the library version whenever a consumer must see a change.
- Dependency floor: the consumer's version of each package the library depends on is at least the library's. A consumer pinned lower validates and builds with only a warning,
Detected package downgrade: <PACKAGE_ID> from <LIBRARY_VERSION> to <CONSUMER_VERSION>, then fails at run time loading the library's assembly version (Could not load file or assembly '<PACKAGE_ID>, Version=…'). Treat that warning as an error: raise the consumer's dependency to the version it names.
Library Patterns
| Pattern | Shape | Example |
|---|---|---|
| Wrapper | Bundle related operations into one higher-level activity | OpenExcelAndReadSheet instead of Open Workbook + Read Range |
| Connector | One library per corporate system — single source of auth, selectors, business rules | CompanyERP.Library owns all ERP interactions |
| Framework | Scaffolding consumers extend (REFramework-style) | State machine with extension points |
| Data access | Centralize database/API access behind typed activities | GetCustomerById returns a row from any backend |
Pitfalls
- Never name a library project
lib— collides with the NuGet package folder layout; consumers fail to compile. - A workflow file and one of its arguments must not share the same name — publishing crashes on the name collision.
- Never set
ImplementationVersionon the XAMLActivityBuilder— a framework bug silently drops the library's argument mappings.
Open this reference as its own page
Invoking PowerShell from RPA Workflows
Default: Use a Coded Workflow Instead
When the impulse is "drop into PowerShell," reach for a coded workflow ([Workflow] in a .cs file) first. A coded workflow runs in-process, surfaces real exceptions, and lives in one file with the rest of the project.
Reach for PowerShell only when:
- The script needs Windows-admin cmdlets (
Get-ADUser,Mount-*, etc.) awkward to call from .NET. - The project already has
.ps1scripts you must edit (don't rewrite for its own sake). - Logic is genuinely PS-shaped (modules, pipeline-style data flow).
For SharePoint REST, HTTP uploads, JSON parsing, file mangling — write a coded workflow. See coded-vs-xaml-guide.md.
When You Need PowerShell — Use the InvokePowerShell Activity
UiPath.Core.Activities.InvokePowerShell<T> (UiPath.System.Activities) is the supported path. Do not shell out via Invoke Process + powershell.exe — that path requires manual quote escaping, exit-code parsing, and a status-file dance. InvokePowerShell handles parameter binding and output collection directly, and exceptions propagate as activity faults.
Properties
| Property | Type | Notes |
|---|---|---|
CommandText |
InArgument<string> |
Required. Script body or single command. |
IsScript |
InArgument<bool> |
true → multi-line script. false → single cmdlet invocation. |
Parameters |
typed collection | Named bindings passed in. Verify the element type via uip rpa activities get-default-xaml --activity-class-name "UiPath.Core.Activities.InvokePowerShell\1"`. |
Input |
InArgument<IEnumerable> |
Pipeline input ($input inside the script). |
Output |
OutArgument<IEnumerable<T>> |
Collected results. T is the activity's generic type argument (e.g. PSObject, string). |
PowerShellProcess |
enum | WindowsPowerShell32 / WindowsPowerShell64 / PowerShellCore. Pin the runtime explicitly. |
ContinueOnError |
InArgument<bool> |
Default false. PS exceptions propagate as activity faults. |
Minimal Pattern
<ui:InvokePowerShell x:TypeArguments="x:String"
CommandText="[scriptBody]"
IsScript="True"
PowerShellProcess="WindowsPowerShell64"
Output="[psOutput]" />
For typed parameter bindings, use the Parameters collection instead of building a command line — no string concatenation, no quote escaping. Look up the element type with activities get-default-xaml before authoring.
Choosing PowerShellProcess
| Value | Runtime | When to use |
|---|---|---|
WindowsPowerShell64 |
Windows PowerShell 5.1, 64-bit | Default for Windows robots; broadest cmdlet compatibility. |
WindowsPowerShell32 |
Windows PowerShell 5.1, 32-bit | Legacy 32-bit modules only. |
PowerShellCore |
PowerShell 7+ | Cross-platform. Requires pwsh installed on the robot. Needed for 7+-only features (Invoke-WebRequest -InFile, ConvertFrom-Json -AsHashtable, ternary, null-conditional, &&/||). |
Always set PowerShellProcess explicitly so a robot upgrade does not silently change the runtime.
Last-Resort Invoke Process
Some scenarios force a direct shellout — a vendor script with exact-CLI requirements, or an interactive session. In that case:
- Pin the executable.
FileName="powershell.exe"for 5.1,FileName="pwsh.exe"for 7+. Do not rely on PATH. - Escape quotes in every value embedded in
Arguments. A single"or'in a path silently shifts every later positional arg.- VB:
value.Replace("""", """""") - C#:
value.Replace("\"", "\"\"")
- VB:
- Status by file, not stdout.
Invoke Processreturns the exit code only. Wrap the script body intry { … } catch { Out-File -FilePath $statusFile -InputObject ("ERROR: " + $_.Exception.Message); exit 1 }so failures are never silent. Read the file after, then delete it.
Anti-Patterns
- Defaulting to PowerShell when a coded workflow would do. See § Default.
- Using
Invoke ProcesswhenInvokePowerShellworks. Skipping the typed activity for no reason triples the gotcha surface. - Driving UI from PowerShell. Use UiPath UIAutomation activities — the UIA package guide (
{PROJECT_DIR}/.local/docs/packages/UiPath.UIAutomation.Activities/ui-automation-guide.md) MUST be read IN FULL first (SKILL.md Rule 7). - Omitting
PowerShellProcess. A robot upgrade can silently land your script on a different runtime.
Open this reference as its own page
REFramework Guide
Patterns for building and customizing Robotic Enterprise Framework projects on Windows, Portable, or Legacy targets. State-machine internals are in legacy/activity-docs/_REFRAMEWORK.md — that guide's architecture sections are mode-agnostic.
Template Configuration File
The configuration file depends on the template the project was created from. Check which file Data/ holds before following any configuration step below.
| Template | File | Holds |
|---|---|---|
| Windows and Portable, template 26.10 | Data/Config.json |
Objects Settings and Constants; values keep their JSON type (number, true/false, text) |
| Windows - Legacy, and earlier templates (template 25.10 ships it for Windows too) | Data/Config.xlsx |
Sheets Settings, Constants (Name/Value rows) and Assets |
Where each file keeps what the rest of this guide refers to:
| Item | Config.json |
Config.xlsx |
|---|---|---|
| The queue | Selected on Get Transaction Item in Framework\GetTransactionData.xaml; an empty folder means the process's folder. The activity ships empty, and validation fails with Value for a required activity argument 'Queue name' was not supplied until a queue is selected. Studio records the queue as a resource of the project |
OrchestratorQueueName in Settings (case-sensitive, must match the queue in Orchestrator) and optionally OrchestratorQueueFolder. The template ships the sample value ProcessABCQueue, which passes a non-empty check (Not String.IsNullOrEmpty(in_Config("OrchestratorQueueName").ToString())): blank or remove the row in a project without a queue |
| Removing the queue (tabular, single-shot) | Nothing to change in the file; the item fetch that replaces Get Transaction Item drops it | Blank or remove OrchestratorQueueName |
| Assets | No assets section: read each asset with Get Asset or Get Credential in the workflow that uses it (credentials typically in InitAllApplications.xaml) |
Listed on the Assets sheet; InitAllSettings.xaml loads each into Config at start. Names must match Orchestrator exactly (case-sensitive) |
Value types in Config |
Int64, Boolean or String, as written in the file: a C# unboxing cast such as (int)in_Config["MaxRetryNumber"] throws InvalidCastException |
String |
When to Use REFramework
Use:
- Multi-item transactional processing (invoices, queue items, data rows).
- Production-grade retry, logging, and exception handling.
- Multi-robot horizontal scaling on a shared Orchestrator queue.
Don't use:
- Simple linear processes (read → do one thing → exit). Plain
Sequenceis enough. - Attended automations with continuous user interaction.
- Single-call jobs under ~30 seconds total. The four-state ceremony costs more than it saves.
The Four States
| State | Role |
|---|---|
Init |
InitAllSettings.xaml reads the configuration file → Config dictionary; KillAllProcesses.xaml; InitAllApplications.xaml opens/authenticates apps. |
Get Transaction Data |
GetTransactionData.xaml returns the next item or Nothing. Nothing → End Process. |
Process Transaction |
Process.xaml (your business logic) → SetTransactionStatus.xaml (Success / BusinessRuleException / System Exception). |
End Process |
CloseAllApplications.xaml runs on every exit (success or abort). |
Full state machine, transitions, and per-state counter semantics: legacy/activity-docs/_REFRAMEWORK.md § State Machine Architecture.
Execution Mode: Queue-Driven (Canonical)
The default and most common mode. Dispatcher project populates an Orchestrator queue; this Performer project consumes one item per transaction. Multi-robot parallelism comes for free via queue locking.
Wiring — keep the template as-is. The shipped REFramework is built for this mode end-to-end.
- Set the queue where the template takes it (§ Template Configuration File).
Framework\GetTransactionData.xaml: uses theGet Transaction Itemactivity. Returns aQueueItemorNothing(queue empty → End Process).Framework\Process.xaml: implement business logic. Access fields via:in_TransactionItem.SpecificContent("FieldName").ToString() in_TransactionItem.Reference in_TransactionItem.Priority in_TransactionItem.DueDateFramework\SetTransactionStatus.xaml: keep the three Set Transaction Status calls — they update item status in Orchestrator.
Dispatcher pattern (separate project). Read input data, then for each row emit Add Queue Item with a unique Reference, optional Priority / DueDate, and the fields as SpecificContent. Dispatcher does not need REFramework — a simple Sequence is sufficient.
Concurrency. Orchestrator locks each item to one robot for the duration of processing. Design Process.xaml stateless so any robot can pick up any item. To scale throughput, add robots — do not add intra-robot parallelism.
Execution Mode: Tabular Data
Single robot, no Orchestrator queue. Source data is an Excel/CSV/DataTable. The Academy course "REFramework with Tabular Data" (v2024.10) is the reference pattern.
Wiring — customize these surfaces.
- Configuration: add
DataSourcePathandDataSourceSheettoSettings; remove the queue (§ Template Configuration File). Framework\InitAllSettings.xaml(or a custom init step): Read Range →io_dt_TransactionData. Read the source once, not per transaction — repeated reads cause file locks and waste cycles.Framework\GetTransactionData.xaml:
AssumesIf in_TransactionNumber > io_dt_TransactionData.Rows.Count Then out_TransactionItem = Nothing ' signals "no more data" Else out_TransactionItem = io_dt_TransactionData.Rows(in_TransactionNumber - 1) End IfTransactionNumberis 1-indexed (Main.xamlstarts it at 1;SetTransactionStatus.xamlincrements it). If your template starts at 0, use>=and drop the- 1.Framework\Process.xaml: access fields viain_TransactionItem("ColumnName").ToString().Framework\SetTransactionStatus.xaml: delete the three Set Transaction Status activities. They target Orchestrator queues and have no purpose here. Replace with a status-column write-back to the source DataTable, an output Excel/CSV, orLog Messagecalls keyed by row index.
Type migration. Changing TransactionItem's type from QueueItem to DataRow cascades across every TransactionItem argument in the Framework workflows and every matching InvokeWorkflowFile binding in Main.xaml. Update them together or InvokeWorkflowFile reports argument-mismatch errors at design time. See Gotchas § type migration for the file/argument list.
Execution Mode: Single-Shot
One execution, no transaction loop. Useful for scheduled jobs that just need REFramework's init/cleanup discipline (open apps, do one thing, close apps).
Wiring.
- Remove the queue (§ Template Configuration File).
Framework\GetTransactionData.xaml: return a sentinel on call 1,Nothingon call 2:If in_TransactionNumber = 1 Then out_TransactionItem = New Object() ' placeholder, NOT New QueueItem() Else out_TransactionItem = Nothing End IfFramework\Process.xaml: implement the single unit of work.in_TransactionItemis a sentinel — ignore it.Framework\SetTransactionStatus.xaml: delete the three Set Transaction Status activities (same reason as tabular). Log-only is fine.
Type migration. Type TransactionItem as System.Object across every Framework workflow and every InvokeWorkflowFile binding. See Gotchas § type migration.
Exception Handling Strategy
REFramework owns the per-transaction retry/counter flow below. For error-handling patterns outside REFramework — Try/Catch discipline, Retry Scope, ContinueOnError, Throw/Rethrow, screenshot-on-error, and the Global Exception Handler — see error-handling-guide.md. Do not add a Global Exception Handler to a REFramework project (it conflicts with the framework's per-state Try/Catch).
| Exception | Class | Retry? | Counter behavior |
|---|---|---|---|
| Business Rule Exception | UiPath.Core.BusinessRuleException |
No — data won't fix itself | ConsecutiveSystemExceptions resets to 0 |
| System Exception | System.Exception (any other) |
Yes — retry per transaction up to MaxRetryNumber; re-initialize apps between retries |
ConsecutiveSystemExceptions increments; hitting MaxConsecutiveSystemExceptions aborts to End Process |
Throw business exceptions explicitly in Process.xaml:
Throw New BusinessRuleException("Invoice amount cannot be negative")
Do NOT wrap Process.xaml in a catch-all TryCatch — the framework's outer handler is what classifies and routes the exception. Catch only exceptions you intend to translate to a BusinessRuleException.
Counter semantics — MaxRetryNumber (per transaction, resets per item) vs MaxConsecutiveSystemExceptions (global, resets on any success or BusinessRuleException): see legacy/activity-docs/_REFRAMEWORK.md § MaxRetryNumber vs MaxConsecutiveSystemExceptions.
Configuration Management
- Store all configurable values in the configuration file (§ Template Configuration File):
Settingsfor values edited per environment,Constantsfor values that rarely change. - Sensitive values (credentials, API keys, tokens) → Orchestrator Assets, never values in the configuration file: it ships in the package in clear text.
- Read assets where the template takes them (§ Template Configuration File).
- Convert every value explicitly, as the template does:
Convert.ToInt32(in_Config("MaxRetryNumber")),Convert.ToBoolean(in_Config("ShouldMarkJobAsFaulted")),CDate(in_Config("Deadline")). The type a value arrives as depends on the template (§ Template Configuration File). - Guard missing keys: check
in_Config.ContainsKey(<name>)or set defaults before first read. - Never hardcode paths, URLs, credentials, or environment-specific settings in workflows. Always indirect through
in_Config(<name>).
Idempotency and Concurrency
Init and Close Run More Than Once (All Modes)
System Exception in Process.xaml → SetTransactionStatus.xaml runs CloseAllApplications.xaml, then Init reruns InitAllApplications.xaml. Fault inside InitAllApplications.xaml → End Process → CloseAllApplications.xaml on a half-initialized state.
InitAllApplications.xamlmust be safe to rerun: open only what is not open, never a second instance.CloseAllApplications.xamlmust be safe on unopened resources: null-check each, close each in its own Try/Catch, null the handle after closing.- Hold non-UI resources (database connections, API/mail/storage clients) in a context object
Main.xamlcreates (Variable.Default) and passes In; Init sets its fields. Never return them asout_*of Init — they leak when Init faults (xaml/common-pitfalls.md § Out and InOut Arguments When the Callee Faults).KillAllProcesses.xamldoes not release in-process handles.
Retried Transactions (Queue-Driven)
Performer workflows must be safe to retry. The framework re-executes Process.xaml after a System Exception with the same TransactionItem.
- Avoid double-posting (check-then-act, or use idempotency tokens from the source system).
- Avoid relying on in-memory state from a prior transaction — design stateless.
- Orchestrator handles queue-item locking; do not add custom locking logic.
- Multiple robots on the same queue: each locks one item while processing. To scale throughput, add robots — not intra-robot parallelism.
- Validate
SpecificContentfields at the start ofProcess.xaml— don't trust the Dispatcher.
Gotchas
Don't return New QueueItem() as a sentinel in non-queue modes
Framework\SetTransactionStatus.xaml gates its Orchestrator calls on in_TransactionItem.GetType is GetType(UiPath.Core.QueueItem). New QueueItem() satisfies this check — so a synthetic empty QueueItem returned from a tabular or single-shot GetTransactionData.xaml cascades into 6 retries × 3 branches of OrchestratorHttpException: 404 (Not Found).
Right fix: delete the Set Transaction Status activities from SetTransactionStatus.xaml for non-queue modes (see the per-mode wiring above) and return Nothing / non-QueueItem sentinels from GetTransactionData.xaml.
Type migration cascade
If you migrate TransactionItem's type away from QueueItem (tabular → DataRow or Object; single-shot → Object), update every site, not just Main.xaml's variable:
| File | Argument |
|---|---|
Main.xaml |
TransactionItem variable |
Framework\GetTransactionData.xaml |
out_TransactionItem |
Framework\Process.xaml |
in_TransactionItem |
Framework\SetTransactionStatus.xaml |
in_TransactionItem |
Framework\RetryCurrentTransaction.xaml |
in_TransactionItem (if present) |
Main.xaml InvokeWorkflowFile bindings |
every in_/out_/io_TransactionItem binding |
Tests\GetTransactionDataTestCase.xaml, Tests\ProcessTestCase.xaml |
the out_TransactionItem / in_TransactionItem bindings of their invokes |
Updating one file but not the others surfaces as InvokeWorkflowFile argument-mismatch errors at design time.
Template test cases fall behind the framework files
The template ships test cases under Tests\, registered as test cases in project.json, that invoke the framework workflows and Main.xaml with the template's own arguments. An argument added to a framework workflow leaves their invokes without it: build reports only a missing-argument warning, and the test case runs the workflow with that argument unset. Bind every added argument in each test case, or delete the test cases and their registration when the project does not keep framework tests. MainTestCase.xaml runs the whole process, so running it is a real job against the applications and data the configuration names.
Waits inside Get Transaction Data ignore the stop signal
Main.xaml checks Should Stop once per Get Transaction Data call, before invoking GetTransactionData.xaml. A GetTransactionData.xaml that loops — polling a mailbox or folder, waiting between passes until an end time — holds the job past an Orchestrator Stop for as long as it loops. Check Should Stop before each wait inside the loop and return Nothing when a stop is requested.
A failure inside End Process does not fault the job
End Process wraps CloseAllApplications.xaml in a Try Catch whose catch logs the failure and runs KillAllProcesses.xaml; its Finally ends the job faulted only when SystemException is set. Close-surface work that must fail the job when it fails — a final report or mail, a clean-up the run depends on — contains each of its steps, so a failed step still lets the others run and the workflow returns, and carries the failure out of CloseAllApplications.xaml as an out argument that Main.xaml assigns to SystemException.
Advanced: one SetTransactionStatus.xaml for all modes
If you want a single SetTransactionStatus.xaml that handles all three modes (rare — usually it's cleaner to delete the Orchestrator calls in non-queue modes), type in_TransactionItem as System.Object and replace the three FlowDecision conditions with a type-safe guard:
TypeOf in_TransactionItem Is UiPath.Core.QueueItem AndAlso DirectCast(in_TransactionItem, UiPath.Core.QueueItem).QueueDefinitionId > 0
TypeOf ... Is short-circuits on non-QueueItem references; QueueDefinitionId > 0 filters out empty New QueueItem() instances. Requires the full Object-typed migration above.
Customization Checklist
Before first run:
- Pick execution mode — queue-driven / tabular / single-shot.
- Queue per mode. Queue-driven: set the queue; tabular and single-shot: remove it, sample value included (§ Template Configuration File).
- Configure
GetTransactionData.xamlfor the chosen mode. Never returnNew QueueItem()as a sentinel in non-queue modes — returnNothing(terminating) or a non-QueueItemvalue. - For tabular / single-shot: delete the three Set Transaction Status activities from
SetTransactionStatus.xaml. Replace with status-column write-back or log-only. - For tabular / single-shot: migrate every
TransactionItemargument type (see Gotchas § type migration). -
InitAllApplications.xaml— implement app-open/login for every application the process touches; rerun-safe (§ Init and Close Run More Than Once). -
CloseAllApplications.xaml+KillAllProcesses.xaml— graceful close + force-kill fallback for every app process name; Close safe on unopened resources (§ Init and Close Run More Than Once). - Template test cases under
Tests\bind every argument the framework workflows gained, or are deleted with their registration (see Gotchas § template test cases). - Classify exceptions in
Process.xaml— throwBusinessRuleExceptionfor data issues; let everything else propagate. - Move secrets to Orchestrator Assets — credentials, API keys, environment-specific URLs.
- Set
MaxRetryNumber = 0during development to surface failures fast; restore the production value before deployment. - Verify: run a synthetic transaction through every exit branch (Success, BusinessRuleException, System Exception → retry, System Exception → abort).
Open this reference as its own page
Remote Session — Live Authoring and Remote Debug/Run on an Orchestrator Unattended Robot
The uip rpa remote group connects the local project to a remote robot — an Orchestrator unattended robot — and operates on it: configure the target, open and close the remote session, execute shell commands, transfer files both ways. Every remote operation acts on the configured remote target, stored per project by remote configure.
When to Use
- Design a workflow on a remote machine — the target application exists only on the remote machine, or UI-heavy design should run there so the user's own machine stays free → Live Authoring. Live Authoring is a superset of Remote Run Only: in the same session, also debug/run the workflow on the remote machine — do NOT switch to Remote Run Only for that.
- Only debug/run a locally designed workflow on a remote machine (no remote design work, no Live Authoring target configured) → Remote Run Only.
Authoring is unchanged: create, edit, and validate the workflow locally per the normal skill workflow.
Remote Session Modes
The mode is set on remote configure with --live-authoring or --remote-run-only.
Live Authoring (--live-authoring) |
Remote Run Only (--remote-run-only) |
|
|---|---|---|
| Connection | Persistent — one long-lived remote session job on the robot | None |
Debug / run with --remote |
Executes on the remote machine, over the session | Each run/debug session is an Orchestrator job of its own |
remote exec, remote upload-file, remote download-file |
Served by the session — return in seconds | Use Live Authoring |
Remote UI Automation (the uip rpa uia group in remote mode — syntax in the UIA docs), remote screen streaming |
Available | Not available |
remote start / remote stop |
Open / close the session | Not applicable — remote start fails |
| Default | — | Yes, for a target that never had a mode stored |
Choose the mode:
- Live Authoring when the workflow is designed on the remote machine — the target application exists only there, or the design work should not occupy the user's machine. It covers everything Remote Run Only does: debug/run with
--remoteexecutes on the remote machine over the session. - Remote Run Only when the workflow is designed locally and only debug/run must happen on the robot.
- Never downgrade Live Authoring to Remote Run Only to debug/run. When the stored mode is Live Authoring, keep it — debug/run within it.
The two flags are mutually exclusive. Passing neither keeps the stored mode. Switching from Live Authoring to Remote Run Only releases the session.
Live Authoring Known Limitations
- Live Authoring is unavailable on Serverless robots.
- Live Authoring is unavailable on attended robots.
- Live Authoring is unavailable on robots that can run only background jobs.
For a Serverless or attended robot, tell the user Live Authoring is not supported on it and ask for a different target (Rule 3). A background-only robot becomes a target once prepared — ask the user whether to prepare it (Rule 11).
Critical Rules
- Run
uip rpa remote statusfirst, at the start of every task. It is read-only. If the stored target already matches the intended folder/machine/robot/runtime and mode (a Live Authoring target also matches a debug/run-only task), do NOT reconfigure — in Live Authoring withremoteSessionEnabled: truethe session is already open: proceed directly to the work, noremote start; in Live Authoring withremoteSessionEnabled: falserunuip rpa remote start; in Remote Run Only proceed directly to debug/run. Configure only when no target is stored or it differs (§ Session Lifecycle). - IMPORTANT — always pass
--robotonconfigure. The CLI lists it as optional (falls back to the machine's default identity), but the remote connection does not work without it. In Live Authoring,configureitself fails withCould not start remote debug session. Foreground process requires you to have an unattended robot with credentials defined; in Remote Run Only,configuresucceeds and every later operation fails with that error. Either way the broken target (robot: null) is stored — reconfigure with--robot. - Ask the user which target to use. Unless the user already named the folder/machine/robot/runtime, look up the candidates from Orchestrator with the uip CLI and ask which to use — never silently pick one (§ Discovering Option Values).
- Pass the mode flag explicitly on every
configure. Pick--live-authoringor--remote-run-onlyfrom § Remote Session Modes; do not rely on whatever mode is stored. Live Authoring is a superset of Remote Run Only — when the target is in Live Authoring, debug/run there and never reconfigure it to--remote-run-only. - Always run
uip rpa remote stopwhen Live Authoring work is finished — also when abandoning the task or after an unrecoverable error. The session job holds an unattended runtime on the robot; on a machine with a single unattended runtime it blocks every other job until it is stopped.stopMUST be the last remote command. - Orchestrator sign-in required. On
not authenticated/401/403, sign in with the uip CLI per cli-reference.md § Authentication, then retry. - The remote filesystem is not directly accessible — transfer first. To read a remote file,
download-fileit and read the local copy. To use a local file on the remote machine,upload-fileit first and reference the remote path. Always use absolute remote paths. execverdict = the trailing JSON envelope. The command's stdout and stderr stream to local stdout ahead of the envelope; read the command output from the streamed lines and the verdict fromResult/Messageonly (§ Execute a Shell Command on the Remote).- Use
--output jsonon every command whose output is parsed, and pass--project-dir "<PROJECT_DIR>"on everyuip rpa remotecommand. The target is stored per project; without the flag the current directory is used, and outside a project folder every command fails withNot a UiPath project at '<DIR>': project.json is missing. - Run/debug verdict = outer
Result/ innerHasErrors— same as local runs, never log-entry levels (SKILL.md Common Rule 8a). - No usable target → ask the user whether to prepare an unattended robot in Orchestrator. Never prepare one unasked. User agrees → § Prepare a Remote Target in Orchestrator. User declines → ask for another folder or target, or stop.
Session Lifecycle
Check the stored target (Rule 1):
uip rpa remote status --project-dir "<PROJECT_DIR>" --output jsonAlready configured and matching —
targetisUnattendedRobot; folder/machine/robot/runtime andliveAuthoringmatch the intent;liveAuthoring: truematches a debug/run-only task too (§ Readingremote status):Live Authoring,
remoteSessionEnabled: true→ the session is already open; truststatusand proceed to step 4 — do NOT runremote start. If a later remote command reports that no session is open, runremote startthen and retry the command.Live Authoring,
remoteSessionEnabled: false→ open the session:uip rpa remote start --project-dir "<PROJECT_DIR>" --output jsonRemote Run Only → nothing to start; proceed to § Debug / Run a Workflow on the Remote.
Not configured, or different →
remote configure(§ Configure a Remote Target). In Live Authoring,configurealso opens the session — no separatestartneeded. No usable robot or host in the folder → ask the user whether to prepare a target (Rule 11).Work — debug/run with
--remote; in Live Authoring alsoexec,upload-file,download-file, and remote UI Automation.Finish (Live Authoring) — close the session (Rule 5):
uip rpa remote stop --project-dir "<PROJECT_DIR>" --output jsonThe target stays stored. Next task: step 2 applies —
statusshowsremoteSessionEnabled: false, soremote startreopens the session without reconfiguring.
| Command | Behavior |
|---|---|
configure |
Resolves and stores the target and mode, then connects. In Live Authoring it blocks until the session job is running — tens of seconds; do not wrap it in a short timeout. Reconfiguring replaces the stored target. A configure that fails to resolve a name (folder, machine, robot, runtime) keeps the previous target and leaves a running session untouched; one that fails while connecting (e.g. missing --robot) stores the new target |
start |
Opens the Live Authoring session → "Remote session ready.". No-op when the session is already open. Fails with no target (Remote debugging is not configured for an unattended robot…) or in Remote Run Only (The remote connection is in Remote Run Only mode…) |
stop |
Closes the session and releases the robot → "Remote session stopped.". Always succeeds — also when no session is running or no target is configured |
status |
Read-only — changes nothing, starts nothing |
Reading remote status
{
"Result": "Success",
"Code": "RemoteStatus",
"Data": {
"success": true,
"target": "UnattendedRobot",
"remoteSessionEnabled": true,
"liveAuthoring": true,
"folder": "<FOLDER_PATH>",
"robot": "<RESOLVED_ROBOT_NAME>",
"machine": "<MACHINE_NAME>",
"runtime": "<RESOLVED_RUNTIME_LABEL>"
}
}
| Field | Meaning |
|---|---|
target |
UnattendedRobot — a remote target is in effect. LocalMachine — no target (not configured, or the backend restarted); the other fields are then absent |
remoteSessionEnabled |
true after configure / start — the session is open, skip remote start; false after stop — run remote start before remote work |
liveAuthoring |
true — Live Authoring; false — Remote Run Only |
folder, machine |
Resolved folder path and machine name |
robot |
Resolved robot name — may differ from the account name passed to --robot. null means --robot was omitted: reconfigure with it (Rule 2) |
runtime |
Pinned host as <HOST> - <HOST>\<ACCOUNT>; null when --runtime was omitted and Orchestrator picks the connected session |
Prepare a Remote Target in Orchestrator
Prepare a target only when the user asks for it or agrees when asked (Rule 11). Ask when § Discovering Option Values finds no usable robot or host, or when the intended robot shows hasCredentials: false. The target is an unattended robot: a robot account on a dedicated machine (VM or server) whose Robot connects to Orchestrator as unattended (machine key or client credentials). Attended robots are not supported (§ Live Authoring Known Limitations).
Rules for Preparing a Target
- Run every Orchestrator check and change through the
uipath-platformskill — it owns the commands for folders, users, robots, machines, and licenses. Skill unavailable → walk the user through the same changes in the Orchestrator web UI. - Check each item before changing it. Change only items that fail.
- Confirm each change with the user before making it — every change alters shared tenant configuration. No free unattended license in the tenant → stop and tell the user; never take a license from another machine.
- Never ask the user for a password. The user or an administrator enters the Windows credentials in the Orchestrator web UI.
- Shared folder only (e.g.
Shared) — never prepare a target only in a Personal Workspace. - Robot 26.10.0 or later — the floor for every remote target (§ Discovering Option Values, step 3). Older → ask the user to upgrade the Robot; stop until done.
- Steps on the machine belong to the user — installing or upgrading the Robot, connecting it to Orchestrator as unattended. Tell the user what to do and wait for confirmation.
Unattended Robot Checklist
- Robot account assigned directly to the shared folder, with a role that can run jobs. No robot account → ask the user whether to create one; robot accounts are created in Identity (the
uipath-adminskill), then assigned to the folder (uipath-platform). - Foreground automation enabled — the robot's unattended setup holds the real Windows credentials of the account it runs as, so the Robot can start a Windows session or join an existing one; the remote session runs in it. Without them the robot is background-only:
hasCredentials: falseinremote targets, and the session fails withForeground process requires you to have an unattended robot with credentials defined. Credentials come from the user or an administrator (item 4 of § Rules for Preparing a Target). - Machine in the same folder with an unattended license — the machine or machine template is assigned to the folder and has at least one unattended runtime.
- Robot 26.10.0+ connected as unattended — its host shows
Availableinremote targets.
Verify the Prepared Target
- Re-run
remote targetsfor the folder (§ Discovering Option Values, step 2): the robot showsenabled: trueandhasCredentials: true; the machine has anAvailablehost. - Item still failing → re-check it against § Unattended Robot Checklist. Same item failing after two re-checks → stop and report what is missing.
- Continue with § Configure a Remote Target and § Validate After Configuring.
Configure a Remote Target
uip rpa remote configure \
--folder-path "<FOLDER_PATH>" \
--machine "<MACHINE_NAME>" \
--robot "<ROBOT_NAME>" \
--live-authoring \
--project-dir "<PROJECT_DIR>" --output json
Pinned to one host of a machine template (§ When to Pass --runtime):
uip rpa remote configure \
--folder-path "<FOLDER_PATH>" \
--machine "<MACHINE_NAME>" \
--robot "<ROBOT_NAME>" \
--runtime "<RUNTIME_NAME>" \
--live-authoring \
--project-dir "<PROJECT_DIR>" --output json
| Flag | Required | Value |
|---|---|---|
--machine |
Yes | Orchestrator machine name to run the unattended robot on |
--robot |
Yes | Robot/user account name to run as; resolved to the robot in the folder. Listed as optional, but operations fail without it (Rule 2) |
--folder-path |
No | Fully-qualified Orchestrator folder path the machine/robot belong to (e.g. Shared/Finance). Defaults to the backend's current folder — pass it whenever the user named a folder |
--runtime |
No | Connected host of the machine to pin the session to: the host machine name (case-insensitive) or the full <HOST> - <HOST>\<ACCOUNT> label. Ignored for serverless machines. Omitted → Orchestrator picks the connected session |
--live-authoring / --remote-run-only |
One of them (Rule 4) | Session mode — § Remote Session Modes |
When to Pass --runtime
- Pass it when the machine has more than one connected host and the work depends on a specific one — typically Live Authoring where the target application is installed on only one host, or when the user names a host. Without it, Orchestrator may open the session on another host.
- Omit it when the machine has a single connected host — Orchestrator picks that one.
- Never guess the host name. Look up the connected hosts per § Discovering Option Values. A wrong name fails with an error that lists the machine's connected runtimes — offer those to the user (Rule 3).
Discovering Option Values
Look up each value the user has not named with these read-only commands, in order. Skip step 1 when the user already named the folder.
Folder — the
--folder-pathvalue isPath(fully qualified, e.g.Shared/Finance), notName:uip or folders list --output jsonLists the folders the signed-in user can access; add
--allto list every folder in the tenant.Remote targets in the folder — robots, machines, and hosts in one call:
uip rpa remote targets --folder-path "<FOLDER_PATH>" --project-dir "<PROJECT_DIR>" --output jsonExample output (trimmed):
{ "success": true, "folder": "Shared", "robots": [ { "name": "<ROBOT_NAME>", "enabled": true, "hasCredentials": true } ], "targets": [ { "machine": "<MACHINE_NAME>", "host": "<RUNTIME_NAME>", "status": "Available" }, { "machine": "<MACHINE_NAME>", "host": "<RUNTIME_NAME>", "status": "Disconnected" } ] }Field Use robots[].name--robotvalue. Offer only robots withenabled: trueandhasCredentials: true— a disabled or credential-less robot passesconfigureand fails at session start.hasCredentials: false= background-only robot: ask the user whether to fix it (Rule 11)targets[].machine--machinevalue. One row per host, so a machine with several hosts appears in several rowstargets[].host--runtimevalue, passed as-istargets[].statusAvailable— usable host;configuretakes only anAvailablehost as--runtime.Serverless— serverless machine: Remote Run Only (§ Live Authoring Known Limitations),--runtimedoes not apply.Busy,Disconnected,Unresponsive,NoSession,Unknown— not usable now;Disconnectedmeans that host's robot service is not connected to OrchestratorThe number of
Availablehosts per machine decides whether to pass--runtime(§ When to Pass--runtime).When the user already named the robot or machine, narrow the listing:
--robot "<ROBOT_NAME>"lists only the machines that robot can use and the hosts that serve it — the same checkconfigure --robotruns;--machine "<MACHINE_NAME>"lists only that machine's hosts.Robot version of each candidate host — every remote target, in both modes, needs Robot 26.10.0 or later on the host, also when the user named the target.
remote targetsdoes not report the version: read it from the host's session in Orchestrator through theuipath-platformskill, or ask the user to check it in the Orchestrator web UI when that skill is unavailable. Older → the host is not usable: ask the user to upgrade the Robot on it, or pick another host.
Then apply Rule 3: present the candidates and ask the user which to use. Offer only machines with at least one Available host on Robot 26.10.0 or later (step 3) — configure rejects a machine with no connected host; for Remote Run Only, Serverless machines are usable too. Empty robots, or no usable row in targets, means the folder has no usable robot or host; ask the user whether to prepare a target in that folder or use another folder (Rule 11). On not authenticated / 401 / 403, sign in per Rule 6 and retry.
Configure Errors
| Message | Fix |
|---|---|
Folder '<FOLDER_PATH>' not found. Available folders: … |
Pick from the listed folders |
Machine '<MACHINE_NAME>' not found in folder '<FOLDER_PATH>'. Available machines: … |
Pick from the listed machines, or correct --folder-path |
Machine '<MACHINE_NAME>' has no available unattended session in folder '<FOLDER_PATH>' - last reported state: … |
No host of that machine is connected. Ask the user to start the machine and connect its robot service to Orchestrator, or pick another machine |
Robot/user '<ROBOT_NAME>' not found in folder '<FOLDER_PATH>'. |
Re-list the robots in that folder (§ Discovering Option Values, step 2) |
Connected runtime '<RUNTIME_NAME>' not found for machine '<MACHINE_NAME>'. Available runtimes: … |
Pick from the listed runtimes. An empty list means no host of that machine is connected — handle as the "no available unattended session" row |
--live-authoring and --remote-run-only are the two modes of one connection; pass at most one. |
Pass exactly one mode flag |
Could not start remote debug session. Foreground process requires you to have an unattended robot with credentials defined — from configure in Live Authoring, or from later operations in Remote Run Only |
--robot omitted → reconfigure with it (Rule 2). --robot passed → the robot has no credentials (background-only): ask the user whether to fix it (Rule 11) — § Unattended Robot Checklist item 2 |
Later operations fail: Remote debugging is not configured for an unattended robot… |
No target is stored — run configure |
Any remote command: …HelmProjectLoadException: "Not a UiPath project at '<DIR>': project.json is missing…" |
--project-dir is missing or wrong — pass the folder containing project.json (Rule 9) |
Validate After Configuring
Check
remote status(§ Readingremote status):targetisUnattendedRobot,liveAuthoringmatches the chosen mode, and folder/machine/robot/runtime match what was requested.Live Authoring — smoke-test end to end and confirm the host:
uip rpa remote exec --command "hostname" --timeout 60 --project-dir "<PROJECT_DIR>" --output jsonResult: Successproves the session executes commands; the streamed host name must match the pinned--runtimewhen one was set. The call returns in a few seconds when the session is open; 20+ seconds means the command had to start a new session job.Remote Run Only — the first
--remoterun (§ Debug / Run a Workflow on the Remote) is the end-to-end check.
Debug / Run a Workflow on the Remote
Add --remote to run or debug start — the workflow executes on the configured unattended robot instead of locally:
uip rpa run --file-path "<WORKFLOW_FILE>" --remote --project-dir "<PROJECT_DIR>" --output json
uip rpa debug start --file-path "<WORKFLOW_FILE>" --remote \
--breakpoints 'workflowFile=Main.xaml,activityIdRef=Assign_1' \
--project-dir "<PROJECT_DIR>" --output json
--remote affects start commands only (run, debug start, plus the Studio Desktop verbs debug start-from-here / debug test-activity). Mid-session verbs (debug step-over, debug continue, debug state, execution cancel, …) operate on the active session and take no --remote:
uip rpa debug continue --output json
uip rpa execution cancel --output json
- Live Authoring — run/debug travel over the open session. After a
stop, runremote startbefore the next--remoterun. - Remote Run Only — every
--remoterun or debug session is an Orchestrator job of its own; nothing to start or stop. - The debug loop is unchanged from local debugging — breakpoints by
activityIdRef,DebugStatebranching (Paused/Suspended/Completed/Running), locals inDebugDetails. Full loop: debugging.md. - Works with both Studio and Helm backends.
--profiling-mode streamis ignored when running remote; end-of-run profiling delivery still applies.- To read files the run produced on the robot (logs, screenshots, reports), download them (§ Transfer Files).
Execute a Shell Command on the Remote
Use in Live Authoring with the session open. Runs through the remote OS shell — cmd.exe /c on Windows, /bin/sh -c otherwise — as the robot's account, so profile paths resolve to that account's profile.
uip rpa remote exec --command "<COMMAND_LINE>" --timeout <SECONDS> \
--project-dir "<PROJECT_DIR>" --output json
| Flag | Required | Value |
|---|---|---|
--command |
Yes | Shell command line to run (e.g. dir on Windows, ls -la on Linux). With a restored package, may be a path relative to the package folder (e.g. tools\\app.exe --flag) |
--package-id |
No | NuGet package id to restore on the remote machine before running the command. Requires --package-version |
--package-version |
No | Version of --package-id to restore. Required when --package-id is set |
--working-directory |
No | Working directory for the command. Defaults to the restored package folder when a package is restored, otherwise the Robot installation directory on the remote machine |
--timeout |
No | Seconds after which the remote command is killed. Omit for no timeout — set one for any command that could hang |
Reading the result (Rule 8):
- The command's stdout and stderr stream to local stdout before the JSON envelope; the envelope's
Data.outputis empty. Take the command output from the streamed lines and parse only the trailing envelope — never feed the whole stdout to a JSON parser. - stdout and stderr arrive merged, and their relative order is not preserved — do not rely on line order across the two streams.
- Exit code 0 →
Result: Success,hasErrors: false. - Non-zero exit →
Result: Failure,MessagecontainsCommand exited with code <N>., and the CLI process exits 1. - A non-zero exit can still come with complete output:
query userprints its table and exits 1, and PowerShell-Commandexits 1 when its last pipeline hit an error, even one hidden by-ErrorAction SilentlyContinue. Read the streamed lines before deciding the command failed. - Timeout →
Result: Failure,MessagecontainsCommand timed out.
On a Windows robot use cmd.exe syntax (&&, type, dir, rmdir /s /q). The --command text passes through two shells before it runs — your local console (Bash, PowerShell or cmd), then cmd.exe on the robot — and each treats quotes and special characters differently. So that it works from any console:
- Put the whole value in double quotes and use only single quotes inside it.
\"works in Bash and cmd but breaks the command in PowerShell. - Single quotes quote only in PowerShell (write a literal
'as'').cmd.exeignores them, so a path with spaces needs PowerShell. - For a short PowerShell command with none of
$ % " ` | & < > ^, put the code after-Commandwithout quotes and write paths with forward slashes (example below). - For any other PowerShell script, write it to a local
.ps1file with your file-writing tool, upload it withupload-file(§ Transfer Files) to an absolute remote path without spaces, and runpowershell -NoProfile -ExecutionPolicy Bypass -File <REMOTE_SCRIPT_PATH>. Don't use-EncodedCommand: each console needs a different encoder, and error output comes back as#< CLIXMLXML.
Examples:
# Inspect the remote environment (Windows robot)
uip rpa remote exec --command "hostname && whoami" --timeout 60 \
--project-dir "<PROJECT_DIR>" --output json
# Check a directory the workflow writes to
uip rpa remote exec --command "dir C:\Output" --timeout 30 \
--project-dir "<PROJECT_DIR>" --output json
# Run a PowerShell snippet
uip rpa remote exec --command "powershell -NoProfile -Command Get-ChildItem 'C:/Output'" --timeout 60 \
--project-dir "<PROJECT_DIR>" --output json
# Restore a published package and run a tool from its folder
uip rpa remote exec \
--command "tools\\app.exe --flag" \
--package-id "<PACKAGE_ID>" --package-version "<PACKAGE_VERSION>" \
--timeout 300 --project-dir "<PROJECT_DIR>" --output json
Transfer Files
Use in Live Authoring with the session open. Files travel through a temporary Orchestrator bucket that is deleted afterwards.
Download a remote file — logs, screenshots, generated reports, exported data — and read the local copy (Rule 7):
uip rpa remote download-file \
--remote-path "<REMOTE_FILE_PATH>" \
--local-path "<LOCAL_DESTINATION_PATH>" \
--project-dir "<PROJECT_DIR>" --output json
Upload a local file — test data, config files, documents the workflow processes — then reference the remote path in the workflow or an exec command:
uip rpa remote upload-file \
--local-path "<LOCAL_FILE_PATH>" \
--remote-path "<REMOTE_DESTINATION_PATH>" \
--project-dir "<PROJECT_DIR>" --output json
--remote-pathMUST be absolute (e.g.C:\\Temp\\input.xlsx). A relative path resolves against the Robot installation directory on the remote machine — files written there clutter the robot's install.- Parent directories are created on the destination side, in both directions.
- Both directions overwrite an existing destination file without warning —
upload-fileon the remote machine,download-filelocally. - A missing remote file fails with
File not found on the remote machine: <REMOTE_FILE_PATH>; a missing local file fails withCould not find file '<LOCAL_FILE_PATH>'. - Robots are often shared. Before
remote stop, delete the temporary files and folders the task uploaded or created, withexec(e.g.rmdir /s /q "<REMOTE_DIR>"on Windows).
Anti-patterns
- Reconfiguring a target that
remote statusalready shows — in Live Authoring runremote startinstead whenremoteSessionEnabledisfalse, or nothing when it istrue(Rule 1). - Running
remote startwhenremote statusshowsremoteSessionEnabled: true— the session is already open; truststatusand go straight to the work (Rule 1). - Leaving a Live Authoring session running after the work is done — it holds a robot runtime; always
remote stop(Rule 5). - Running
execor a file transfer afterremote stopand leaving — the command reopens the session, which then holds the robot again;stopmust be the last remote command (Rule 5). - Running
remote startin Remote Run Only — there is no session to start; it fails. Switch to Live Authoring when a persistent session, shell/file commands, or remote UI Automation are needed. - Choosing Remote Run Only for design work on the remote machine — it has no remote session.
- Switching a Live Authoring target to Remote Run Only to debug/run — Live Authoring already debugs/runs on the remote machine; switching releases the session and loses remote UI Automation, shell, and file commands (Rule 4).
- Omitting
--robotonconfigure—configurefails in Live Authoring, or succeeds in Remote Run Only and every later operation fails; the broken target is stored either way (Rule 2). - Guessing folder/machine/robot/runtime names — look them up from Orchestrator and ask the user (Rule 3).
- Configuring a machine whose host is not connected —
configurerejects it; pick a machine with a connected, responsive host. - Preparing a target without asking the user — when no usable target exists, ask whether to prepare one; never start on your own (Rule 11).
- Preparing a target only in a Personal Workspace — remote sessions need the robot and machine in a shared folder (§ Rules for Preparing a Target).
- Configuring a robot with
hasCredentials: false— it runs only background processes and the session fails; ask the user whether to enable foreground automation first (Rule 11). - Omitting
--runtimeon a multi-host machine when the application exists on only one host — the session may open on a host without it (§ When to Pass--runtime). - Setting
--runtimefor a serverless machine — the flag is ignored there; it only pins a session on a classic machine. - Wrapping
configure --live-authoringin a short timeout — it blocks until the session job runs, tens of seconds. - Passing
--remoteto mid-session debug verbs — only start commands take it. - Parsing all of
execstdout as JSON — streamed command output precedes the envelope (Rule 8). - Relative
--remote-path— the file lands in the robot's installation directory; use absolute paths. - Passing
--package-idwithout--package-version— the version is required whenever a package is restored. - Omitting
--timeouton anexeccommand that can hang — without it the command runs unbounded on the remote machine.
Open this reference as its own page
Tenant Library Search
Discover libraries already deployed to the tenant feed. Use whenever the user wants to "leverage", "reuse", "find", or "use existing" libraries — typically before adding NuGet dependencies to a new RPA project, or when planning which utilities a project should consume.
Default search target: tenant feed, not local filesystem
The tenant feed is authoritative for org-published libraries. Do NOT search the local filesystem, project folder, NuGet.org, or git grep for "shared library" candidates — those surfaces do not represent what the org has deployed.
CLI surface
uip or libraries list. Returns a curated Data: [{ Key, Title, Version, Authors }] (pass --all-fields for the full DTO). Key is PackageId:Version and is always populated. Title can be null.
# Server-side name search (contains-match), single keyword:
uip or libraries list --search Excel --output json
# Full scan, then filter/rank client-side:
uip or libraries list --limit 1000 --output json
| Flag | Purpose |
|---|---|
-s, --search <term> |
Server-side name contains-match. Single term only — for multi-keyword OR or Authors matching, use --output-filter. |
--feed-id <id> |
Target a specific feed by ID. Defaults to the tenant feed. |
--limit <N> |
Items per call (default 50, at most 1000). Use 1000 with --output-filter: the filter runs only over the rows this call fetched. |
--offset <N> |
Row offset. Use it while the envelope's Pagination.HasMore is true, raising it by the limit each call. With --output-filter, Data holds only the matches, so Data.length says nothing about more pages. |
--sort-by "<field> <asc|desc>" |
Sort. Default Id desc. |
--all-fields |
Return the full library DTO instead of the curated subset. |
--output-filter "<JMESPath>" |
Client-side filter, evaluated after the API returns. Use for multi-keyword OR, Authors matching, or null-Title guarding. |
--search is the simplest path for a single name keyword. Use --output-filter (below) when you need multi-keyword OR, Authors-field matching, or a null-Title guard.
JMESPath filter recipe
Title can be null, so contains(Title, 'X') errors out unless guarded. Always use:
# Single keyword
uip or libraries list --limit 1000 \
--output-filter "[?Title != null && contains(Title, 'Excel')]" \
--output json
# Multi-keyword OR
uip or libraries list --limit 1000 \
--output-filter "[?Title != null && (contains(Title, 'Common') || contains(Title, 'Shared'))]" \
--output json
For case-insensitive matching, lowercase the keyword in the filter and the field: contains(to_string(Title), 'common') || contains(to_string(Title), 'Common') — or run unfiltered and rank in-agent.
Authors-field filter
For orgs that publish libraries with cryptic Titles but a stable Authors value, filter on Authors instead of Title:
uip or libraries list --limit 1000 \
--output-filter "[?Authors != null && contains(Authors, '<OrgName>')]" \
--output json
Combine Title and Authors filters with || when the org uses both conventions inconsistently.
Procedure
Auth preflight. Run a benign call once:
uip or libraries list --limit 1 --output json. IfResult == "Failure"with an auth-related message, surface it and switch to the manual fallback (below). Do NOT retry silently.Extract keywords from the source (user prompt, plan tasks, surrounding workflow names). Cap at 6:
- Org-prefix terms:
Common,Shared,Utils,Helpers,<Company>if known - Capability terms:
Excel,SAP,ServiceNow,Salesforce,Email,PDF,SharePoint,Outlook,Citrix, etc. — drawn from the activities the project will use - Domain terms:
Invoice,Vendor,Banking,Order— drawn from the project name and request
If you have more than 6 candidate keywords, skip the OR-filter and run unfiltered (
--limit 1000, paginate via--offsetwhilePagination.HasMoreistrue); rank in-agent. Splitting a long keyword set across multiple OR-filtered calls is an anti-pattern (#7 below).- Org-prefix terms:
Run one filtered call covering all keywords with the OR pattern above. Single call, not one per keyword — but if
Pagination.HasMoreistrue, repeat that same call with--offset 1000,--offset 2000, … until it isfalse, and merge the matches. Branch on the merged result: ≥1 candidate after ranking → step 5a. 0 candidates → step 5b. Do not loop back to step 2 with new keyword permutations.Rank candidates in-agent.
- Org-prefix match in
TitleorKey(starts withCommon,Shared,<Company>) → rank highest - Capability/domain match in
Title→ rank next - Authors equal to the user's org → boost
- De-duplicate by
Titlekeeping the latestVersion5a. If ≥1 candidate — present top 5 viaAskUserQuestionwithmultiSelect: true. Each option label:<PackageId> <Version> — <Title>. Always include "None / skip" as a non-multiSelect-exclusive option (or describe it as "leave all unchecked"). 5b. If 0 candidates — present a single-select numbered fallback. Do not run more filtered calls with new keywords:
No org-published libraries matched the search. How would you like to proceed?
- Proceed without shared libraries (recommended) — install only public NuGet dependencies
- Search a specific name or prefix — re-run with the team's actual library naming convention
- Provide names manually — name libraries to install even if not yet deployed; flag as
[VERIFY DEPLOYMENT] - Pause and re-authenticate to a different tenant — if libraries live elsewhere
- Org-prefix match in
Record the user's selection. For each accepted library, run
uip rpa packages install --packages 'id=<PackageId>,version=<Version>' --output jsonto add it toproject.json. Verify after install withuip rpa validate --output json.
Skip when
- An SDD already records "Shared libraries referenced" in §16 — those have been confirmed and the package list flows from the SDD. Do not re-prompt.
- The user has explicitly said "no shared libraries" earlier in the session.
- The task is pure UI capture / authoring with no new dependencies.
Manual fallback (auth preflight failed)
If uip is unauthenticated, ask the legacy question:
Tenant library search is unavailable (not authenticated to a UiPath tenant). Provide shared libraries manually?
- Skip — no shared libraries (recommended)
- Yes —
CommonLibrary(the conventional default)- Yes — other (you name them)
- Authenticate first — run
uip login, then re-invoke the skill
Anti-patterns
- Searching the local filesystem first. Tenant is authoritative; local matches do not indicate org adoption.
- Using
--searchfor multi-keyword OR orAuthorsmatching.--searchis a single-term server-side name contains-match only. For OR across keywords or matching onAuthors, use--output-filter. - Passing
--feed-idwithout a reason. It defaults to the tenant feed — only set it to target a non-default feed. - Calling
contains(Title, ...)withoutTitle != nullguard. Tenants commonly hold packages with null Title — the call fails fast withInvalid type: contains() expected ... received type null. - Listing all libraries with no
--limitbump, or paginating past the end. Default 50 truncates large tenants and silently misses candidates. Use--limit 1000for a filtered scan; paginate via--offsetwhilePagination.HasMoreistrue(with--output-filter,Data.lengthcounts matches, not rows fetched). OnceHasMoreisfalse, you have seen the entire feed — stop searching, do not run more filtered queries hoping for hidden matches. - Auto-installing a candidate. Library installation modifies
project.jsonand project compilability — always confirm viaAskUserQuestionbefore invokingpackages install. - One CLI call per keyword, or running more keyword permutations after a zero-result filtered call. Combine keywords into one OR-filtered call. On zero results, escalate to step 5b — do not loop back with new keyword sets hoping for hidden matches.
Open this reference as its own page
Testing Guide
Reference for XAML test automation features in UiPath RPA projects — XAML test case structure, data-driven testing, XAML test activities, execution templates, and mock testing.
For coded test case creation (Given-When-Then, assertions, Before/After hooks), see coded/operations-guide.md § Add a Test Case File.
Table of Contents
- Test Manager Setup (CLI)
- XAML Test Case Structure (Given-When-Then)
- Data-Driven Testing
- XAML Test Activities
- Execution Templates
- Mock Testing (XAML Only) — WIP
Test Manager Setup (CLI)
Linking a project to Test Manager (server connection + default project) can be done headlessly with uip rpa tm, without opening Studio — useful before authoring test cases that reference Test Manager test cases. Commands, ordering constraints (connect before set-default-project, server switches clearing the default project), and reloadHint handling: cli-reference.md § Test Manager. The CLI does not validate the project id against the server; obtain a real id from Test Manager (the runtime uip tm project list tool can list them).
XAML Test Case Structure (Given-When-Then)
XAML test cases use a Given-When-Then structure — three nested <Sequence> elements inside a parent Sequence. The agent generates these directly as XAML.
XAML Structure — Test Case Invoking a Workflow
The core pattern: a parent Sequence with three child Sequences named "... Given", "... When", "... Then". The When section invokes the workflow under test. Verification activities go in Then, except a check of a state that later steps change (a confirmation after a save in an end-to-end flow): it sits right after the step that produces that state, in When or in a workflow When invokes. A verification records its assertion in the test result from any depth.
<!-- Body inside <Activity> (after namespaces/references) -->
<Sequence DisplayName="TestMyWorkflow">
<!-- GIVEN — set up preconditions -->
<Sequence DisplayName="... Given">
<!-- Assign variables, open apps, prepare test data -->
</Sequence>
<!-- WHEN — execute the workflow under test -->
<Sequence DisplayName="... When">
<ui:InvokeWorkflowFile
DisplayName="MyWorkflow - Invoke Workflow File (MyWorkflow.xaml)"
WorkflowFileName="MyWorkflow.xaml"
UnSafe="False">
<ui:InvokeWorkflowFile.Arguments>
<scg:Dictionary x:TypeArguments="x:String, Argument" />
</ui:InvokeWorkflowFile.Arguments>
</ui:InvokeWorkflowFile>
</Sequence>
<!-- THEN — verify results -->
<Sequence DisplayName="... Then">
<!-- VerifyExpression, VerifyExpressionWithOperator, etc. -->
</Sequence>
</Sequence>
Required xmlns for InvokeWorkflowFile:
xmlns:ui="http://schemas.uipath.com/workflow/activities"
Default Values for Test-Case Arguments
A test case authored with an <x:Property Name="in_X" Type="InArgument(x:String)" /> argument should generally bake in a default so uip rpa run --file-path <TestCase>.xaml is runnable without --input-arguments. Use the canonical root-attribute syntax — see xaml/xaml-editing-catalog.md § Setting Default Values for Arguments. The wrong forms (bare attribute, <x:Property.Value>, <InArgument> child of <x:Property>) all produce confusing member not supported errors — the doc explicitly lists them so you don't waste time trying. An argument bound to a Data Service entity takes no default (§ Data Service Entity).
XAML Structure — Execution Template Placeholder
The ui:Placeholder sits in the execution template, where the case runs (§ Execution Templates); a bound case is an ordinary Given-When-Then file:
<Sequence DisplayName="Run case">
<ui:Placeholder
Description="This placeholder activity will be replaced at build time and can only be used within an execution template." />
</Sequence>
Passing Arguments to Invoked Workflows
If the workflow has arguments, pass them as entries of InvokeWorkflowFile.Arguments:
<ui:InvokeWorkflowFile WorkflowFileName="CalculateDiscount.xaml" UnSafe="False">
<ui:InvokeWorkflowFile.Arguments>
<InArgument x:TypeArguments="x:Decimal" x:Key="in_Amount">
<CSharpValue x:TypeArguments="x:Decimal">1500.00m</CSharpValue>
</InArgument>
<InArgument x:TypeArguments="x:Decimal" x:Key="in_DiscountRate">
<CSharpValue x:TypeArguments="x:Decimal">0.10m</CSharpValue>
</InArgument>
</ui:InvokeWorkflowFile.Arguments>
</ui:InvokeWorkflowFile>
project.json Registration
Register every XAML test case in designOptions.fileInfoCollection — this is Common Rule 10 in SKILL.md and applies to both XAML and coded test cases. Test cases live only in fileInfoCollection, never in entryPoints — entryPoints is for executable workflow files in Process projects (e.g. Main.xaml), and test cases are not workflow entry points regardless of project type.
Copy-paste JSON snippet (including publishAsTestCase for coded test cases and dataVariationFilePath for data-driven): ../assets/json-template.md.
Required keys per entry:
editingStatus—"InProgress"on creation;"Publishable"only on explicit user request (see lifecycle note below).testCaseId— fresh GUID, lowercase 8-4-4-4-12 hex (e.g.2d81aebd-fbc1-4a66-8418-be77a34a3a21). Generate via[guid]::NewGuid()in PowerShell oruuidgenon Unix.testCaseType—"TestCase".executionTemplateInvokeIsolated—falseunless the test runs under an execution template that requires isolation.fileName— relative path of the.xamlor.cstest case file from the project root.
Template keys: an execution template is registered as its own entry (templateType ExecutionTemplate), a new-test-case template with templateType TestCase, and a case is bound to its execution template with executionTemplatePath and executionTemplateType on its entry. Shapes: ../assets/json-template.md; behaviour: § Execution Templates.
editingStatuslifecycle: Set to"InProgress"when creating a new test case. Update to"Publishable"only when the user explicitly asks to mark the test case as ready.
What NOT to Do
- Do NOT place verification activities in the When container, except a mid-flow check (§ XAML Structure — Test Case Invoking a Workflow)
- Do NOT forget to add the
xmlns:uinamespace when usingInvokeWorkflowFile
Data-Driven Testing
Data-driven testing executes the same test case multiple times with different input data sets. Each data row represents a separate test scenario.
Data Sources Overview
| Source | Where Data Lives | Best For | Agent Support |
|---|---|---|---|
| Variations files | .variations/ folder in project |
File-based test data committed with the project | CLI, Studio Desktop only: test-data add-variation. Headless: files (§ Adding Test Data via CLI) |
| Test Data Queues | UiPath Orchestrator | Large-scale distributed testing, parallel execution. To be deprecated at a later date | CLI, Studio Desktop only: test-data add-queue |
| Data Service | Data Fabric entity | Centralized, shared test data, filtered per test case; records change without a republish | Files: § Data Service Entity |
For coded data-driven tests using default parameters, see coded/operations-guide.md § Add a Test Case File.
Variations Files (Coded & XAML)
Store test data in the .variations/ folder at the project root. Each JSON file maps to a test case and contains rows of input data.
MyProject/
├── .variations/
│ └── TestProcessInvoice.json
├── TestProcessInvoice.cs
└── project.json
The .variations/ directory is available in all project types (Process, Tests, Library). Data files must be in JSON format.
Adding Test Data via CLI
Two commands attach file and queue sources to a test case. Both register the data source in project metadata, extract arguments from the source schema, and add them to the test case (via Studio's workflow management API for XAML, via Roslyn for coded test cases). A Data Service source is written as files (§ Data Service Entity).
Studio Desktop only. Both commands need a running Studio Desktop with rpa-tool interop; headless Studio does not serve them. Without one (cli-reference.md § Headless Studio (Helm) vs Studio Desktop), write the variations file and the case's
dataVariationFilePathper json-template.md § Data-driven test case and declare one test case argument per field. A Test Data Queue has no headless route: tell the user it needs Studio Desktop.
test-data add-variation — File-based (JSON)
uip rpa test-data add-variation --test-case-path "<TEST_CASE_FILE>" --data-variation-path "<DATA_FILE>" --project-dir "<PROJECT_DIR>" --output json
| Parameter | Required | Description |
|---|---|---|
--test-case-path |
Yes | Relative path to the test case file (.xaml or .cs) |
--data-variation-path |
Yes | Relative path to the JSON data file in .variations/ |
Parses fields from the JSON file and creates one argument per field with matching type and a default value from the first entry.
Example:
uip rpa test-data add-variation --test-case-path "TestProcessInvoice.cs" --data-variation-path ".variations/InvoiceData.json" --project-dir "C:\MyProject" --output json
test-data add-queue — Orchestrator Test Data Queue
Prerequisite: Use the uipath-platform skill to discover queue details (name, ID, folder) before calling this command.
uip rpa test-data add-queue --test-case-path "<TEST_CASE_FILE>" --queue-name "<QUEUE_NAME>" --folder-path "<FOLDER>" --queue-id <ID> --project-dir "<PROJECT_DIR>" --output json
| Parameter | Required | Description |
|---|---|---|
--test-case-path |
Yes | Relative path to the test case (.xaml or .cs) |
--queue-name |
Yes | Name of the Test Data Queue in Orchestrator |
--folder-path |
Yes | Orchestrator folder path |
--queue-id |
Yes | Orchestrator ID of the queue |
Creates an IDictionary<string, object> argument named after the queue (camelCase).
Example:
uip rpa test-data add-queue --test-case-path "TestLoanApproval.cs" --queue-name "loan_applications" --folder-path "Shared" --queue-id 123 --project-dir "C:\MyProject" --output json
Critical: Do NOT rename the auto-generated test data queue argument. If you change its name, data retrieval silently fails.
Data Service Entity
Every record matching the test case's filter is one variation: Test Manager runs the case once per record. Records are queried when the run starts, so records added or edited later need no republish.
Prerequisites:
- Discover / verify entities — run
uip rpa data-fabric-entities list --project-dir "<PROJECT_DIR>" --output jsonto see what is installed and what is available in the connected tenant. (Alternatively, theuipath-platformskill can discover entities directly in Orchestrator.)- Install the target entity into the project if not already installed —
uip rpa data-fabric-entities install --add "<ENTITY_NAME>" --project-dir "<PROJECT_DIR>" --output json. The test case uses the entity's generated type. See cli-reference.md § Data Fabric Entities.
Write the binding as the four files below. Do not use uip rpa test-data add-entity: it runs only in Studio Desktop, takes no filter, leaves the argument and the project.json entry unsaved in the open designer, and writes the entity's first record (user names and emails included) as the argument's default.
<NAMESPACE> = project.json → entitiesStores[0].namespace. <ARG> = entity name in camelCase; keep it exactly, the data binds by this name.
.variations/<ENTITY>_<NAME>.json—<NAME>names the filter (short: the generated setup workflow is named after the file):{"EntityName":"<ENTITY>","TypeName":"<NAMESPACE>.<ENTITY>","Filters":"<BASE64_QUERY>","TestCaseId":"<UUID_V4>","Name":"<NAME>"}TestCaseIdis a fresh GUID, not the case's. At pack, Studio generates from this file a setup workflow with that id (.generated/.setup/Fetch <ENTITY>_<NAME> Test Data.xaml); it queries the entity and passes each record to the case..variations/config.json— append{"filePath": ".variations\\<ENTITY>_<NAME>.json", "dataVariationType": "Entity"}todataVariationFileInfo(create{"dataVariationFileInfo": [...]}when absent).project.json— the case'sfileInfoCollectionentry gets"dataVariationFilePath": ".variations\\<ENTITY>_<NAME>.json", aftertestCaseId(Studio's order).- Test case argument, typed as the entity, no default:
- XAML:
<x:Property Name="<ARG>" Type="InArgument(local:<ENTITY>)" />withxmlns:local="clr-namespace:<NAMESPACE>;assembly=DataService.<NAMESPACE>", namespace importUiPath.DataService.Definitionand<NAMESPACE>, assembly referencesUiPath.DataService.DefinitionandDataService.<NAMESPACE>. - Coded:
[TestCase] public void Execute(<NAMESPACE>.<ENTITY> <ARG>). UiPath.DataService.Activitiesis not needed for the data source alone.
- XAML:
Filters = Base64 of the UTF-8 JSON Studio's Query Builder saves. Written in that form, the builder opens it and saves it unchanged:
{"SelectedFields":null,"Start":0,"Limit":1000,"SortOptions":null,"Expansions":null,"FilterGroup":{"LogicalOperator":0,"QueryFilters":[{"FieldName":"<FIELD>","Operator":"=","Value":"<VALUE>"}],"FilterGroups":[]}}
LogicalOperator:0= All (AND),1= Any (OR).FilterGroupsnests groups of the same shape. Operators are the Data Service query API's (query endpoint).Limit: 1000 is the most a run gets; a higher value returns 1000,0or unset returns 100. Records beyond the limit are dropped without error.SortOptions: leavenull. The builder neither shows nor keeps a sort, and each record runs as its own job. Unsorted records come inIdorder.Filtersempty → every record of the entity.
Run-time behaviour:
- No record matches → Test Manager marks the case Failed without running it ("could not fetch any data"). It runs once a record matches.
- A local
uip rpa runskips the setup workflow, so the argument is null. Bind one record with--input-arguments-file <FILE>, the file holding{"<ARG>": {"<FIELD>": <VALUE>, ...}}keyed by field names.
One Entity for a Project's Test Data
A test project keeps all its Data Service test data in one entity, one record per data row, with three fields:
| Field | Type | Holds |
|---|---|---|
| Data set | text | name of the data set the row belongs to, unique within the project |
| Row order | number, no decimals | row's position in its data set, from 1 |
| Row | long text (MULTILINE_TEXT) |
the row as one JSON object of text values, every field of its data set present, an empty value as "" |
Name the entity after the project and its fields under Data Fabric's naming rules (uipath-platform). Do not type the row field MULTILINE_MAX: list and query reads return only a preview of it (uipath-platform). One entity is one definition, one install and one load, and a data set that gains a field changes no entity; Data Fabric cannot filter on a value inside the row, so criteria on row values run in code after the parse.
- Data source. A case's data source filters the entity on its data set's name (
=); its argument is the entity type. - Rows read during a run. Query Entity Records filters on the data-set field, sorts by the row-order field and pages per the activity's doc; the rows are parsed before use.
- Parse. One coded helper per project (a coded source file) turns a record into its values and reads each as text, number, whole number or flag. It is strict, because a silent default hides a data error: an empty or invalid row, a field the row lacks, or a value that does not convert raises an
ArgumentExceptionnaming the calling workflow, the data set, the row order, the field and the raw value — a credential-like field's value left out — with the original exception asInnerException. A workflow that receives a record or queries rows parses them at its start, before any step uses a value, so a data error fails there and not later as a bareFormatException. - Load. Insert the records from JSON files in batches the record insert accepts, never through a CSV import, which loses text holding line breaks or quotes (
uipath-platform). Check the load by the record count per data set, read back from the server.
Data-Driven Testing Best Practices
- Separate test data from test logic — keep data in external sources, not hardcoded in test cases
- Include both positive and negative scenarios — test expected failures too (invalid inputs, boundary values)
- Name data fields descriptively — use field names like
ExpectedResult,Scenariofor traceability - Keep data sets small and focused — each data set should test one concern; avoid combinatorial explosion
- Use JSON format for
.variations/data files
XAML Test Activities
The UiPath.Testing.Activities package provides XAML-specific test activities beyond what the coded testing service offers.
Verification Activities
| Activity | Purpose | Key Properties |
|---|---|---|
| VerifyExpression | Assert a boolean expression is true | Expression, OutputMessageFormat |
| VerifyExpressionWithOperator | Assert two values with a comparison operator | FirstExpression, SecondExpression, Operator |
| VerifyRange | Assert a value is within (or not within) inclusive bounds | Expression, LowerLimit, UpperLimit, VerificationType |
| VerifyControlAttribute | Assert an output of the one UI activity it wraps | ActivityToTest, OutputArgument, Operator, Expression |
Choose by the check, so the assertion's default message shows the values compared:
| The check | Activity |
|---|---|
| A UI element's value or state against an expected value | VerifyControlAttribute around the activity that reads it: Get Text, Get Attribute, or Check App State's Exists for "is shown" — never a read into a variable and a separate assertion |
| Two values: equal, not equal, contains, a regex, greater or less | VerifyExpressionWithOperator |
| A value inside or outside two bounds | VerifyRange |
| Anything else — starts with, does not contain, case-insensitive, several conditions | VerifyExpression, with an OutputMessageFormat showing the values |
VerifyExpressionWithOperator
Compares two expressions using a comparison operator from the Comparison enum. Both FirstExpression and SecondExpression are InArgument<Object> — they accept any type; relational comparisons rely on the runtime types implementing IComparable.
Properties:
FirstExpression— left-hand value (InArgument<Object>, the actual)SecondExpression— right-hand value / expected (InArgument<Object>)Operator—Comparisonenum. Exact supported values:Equality,Inequality,GreaterThan,GreaterThanOrEqual,LessThan,LessThanOrEqual,Contains,RegexMatch. Any other identifier (e.g.StartsWith,EndsWith,DoesNotContain,Matches) is invalid and rejected atbuildtime —validatedoes NOT catch invalid enum values.OutputMessageFormat— custom format string for the result message; placeholders{LeftExpression},{LeftExpressionText},{RightExpression},{RightExpressionText},{Result},{Operator}TakeScreenshotInCaseOfFailingAssertion(Boolean) — capture screenshot on assertion failureTakeScreenshotInCaseOfSucceedingAssertion(Boolean) — capture screenshot on success
Authoritative reference: {projectRoot}/.local/docs/packages/UiPath.Testing.Activities/activities/VerifyExpressionWithOperator.md. Read the activity doc whenever this skill summary disagrees with it — the activity doc wins.
No "starts with" / "ends with" / "does not contain" operators. For substring containment, use
Contains(assertsFirstExpressioncontainsSecondExpression). For prefix/suffix or "does not contain" assertions, useVerifyExpressionwith a boolean C#/VB expression (e.g.actualValue.StartsWith("foo"),Not actualValue.Contains("bar")). For regex, useRegexMatchand pass the pattern inSecondExpression.
Text operands are compared as patterns, with case.
EqualityandInequalitymatchSecondExpressionas a wildcard pattern against the whole text:*any characters,?one character,#one digit,\escaping each. An expected value holding*,?or#escapes them (PO \#123), orPO #123also matchesPO 1123and not itself.Equality,InequalityandContainsare case-sensitive;RegexMatchis too unless the pattern starts with(?i). A case-insensitive check isRegexMatchwith(?i)and the escaped value, or aVerifyExpression.VerifyControlAttributecompares the same way.
VerifyControlAttribute
Wraps exactly one UI Automation activity and asserts one of its output properties against an expected value: the read and the check are one activity.
Requires UI automation targets. The wrapped activity inspects live UI elements at runtime. The UIA package guide (
{PROJECT_DIR}/.local/docs/packages/UiPath.UIAutomation.Activities/ui-automation-guide.md) MUST be read IN FULL first (SKILL.md Rule 7). The agent must configure the wrapped activity's target usinguia-configure-target. The test case must run against a live application instance.
Properties:
ActivityToTest— the one UI activity whose output is asserted (NGetText,NGetAttribute,NCheckState), its target configured viauia-configure-targetOutputArgument— the name of that activity's output property (TextStringfor Get Text,Existsfor Check App State), a plain name, not an expressionOperator— comparison operator from the sameComparisonenum asVerifyExpressionWithOperatorExpression— expected value, a non-genericInArgumentin element syntax withx:TypeArgumentsTakeScreenshotInCaseOfFailingAssertiondefaults toTruehere,Falseon the other verify activities
Element syntax, validation constraints and example: the activity's own doc ({projectRoot}/.local/docs/packages/UiPath.Testing.Activities/activities/VerifyControlAttribute.md), read before authoring.
Constraints:
- No verify activity may sit inside
ActivityToTest— causes validation error - Windows projects only — hidden in cross-platform projects
Assertion Results
Each verification activity records one assertion in the test case result. Shared properties and their per-activity defaults: package overview § Shared Assertion Properties.
- Title and message — Test Manager stores the assertion's
MessagefromAlternativeVerificationTitle(else theDisplayName) and itsPayloadfromOutputMessageFormat(else the activity's default sentence, e.g.Verification failed. The expression '"abc"' was not containing the expression '"z"'.). Name the check in the title; show the actual values in the format. - Screenshots —
TakeScreenshotInCaseOfFailingAssertion/TakeScreenshotInCaseOfSucceedingAssertionattach a screenshot to that assertion: on Windows the whole desktop, every monitor of the robot's session with every window on it, not the target application; inside a Mobile Automation scope the device screen; on a Linux robot the application of the last UI action. Both are optional (validateandanalyzestay silent when missing); set both explicitly when screenshots are wanted. - Screenshot files — the project settings Testing › Generic
KeepScreenshots(True) andScreenshotsPathkeep each screenshot as a file in that folder (empty: the temp folder) and logScreenshot available: <path>; otherwise the file is deleted once taken. Every verify activity reads them through hidden arguments of the same names, which Studio writes as{x:Null}. - Logs — each verification logs its own
Payload:Infoon pass,Erroron fail. ALog Messagerepeating a verification's result is redundant. - Failure — a check failing with
ContinueOnFailureTrue(default) marks the case Failed without stopping it, and a local run's verdict does not show it (debugging.md § Output Format).
Given-When-Then in XAML
The Given-When-Then structure is three nested <Sequence> elements — not separate activity types. See § XAML Test Case Structure above for the full XAML patterns and agent workflow.
Place verification activities inside the "... Then" Sequence, mid-flow checks excepted (§ XAML Structure — Test Case Invoking a Workflow).
XAML Test Activity Gotchas
- BookmarkResumptionHelper — assert activities require this extension. Studio adds it automatically, but manual XAML construction must include
metadata.RequireExtension<BookmarkResumptionHelper>()in CacheMetadata - VerifyControlAttribute nesting — cannot nest one inside another
- Platform restrictions —
VerifyControlAttributeand some testing activities are Windows-only and may not work in Portable projects
Execution Templates
Execution templates wrap test cases at runtime with predefined execution conditions. They let you reuse the same test case logic across different environments, configurations, or application states without duplicating test code. Setup, teardown, a timeout and failure capture written in the template apply to every case it wraps.
When to Use Execution Templates
- Run the same test case against multiple environments (dev, staging, prod)
- Apply different browser/application configurations per run
- Set up common preconditions (login, navigation) shared across many test cases
- Override argument values at runtime without modifying the test case
- Apply a timeout, failure capture or teardown (closing the application) to every case
How Execution Templates Work
- Create an execution template: right-click the Templates folder → Add → Execution Template. On disk it is a workflow in
.templates\holding oneui:Placeholder(§ Execution Template Placeholder), registered as anExecutionTemplateentry; each case it wraps names it withexecutionTemplatePathandexecutionTemplateType"Local"(§ project.json Registration). A case whose entry names no template runs bare. - Define variables and arguments in the template that match names in the test case
- At runtime, Studio merges the test case and template into a temporary file:
- Arguments with matching names are linked — template values override test case defaults
- Variables with matching names are linked — template values take precedence
- Non-overlapping arguments/variables from both files are included as-is
uip rpa packwrites.generated\<case path>.xamlfor each bound case: the template with its Placeholder replaced by an Invoke Workflow File of the case. These generated files are the package's entry points (eachuniqueIdis the case'stestCaseId), so Orchestrator and Test Manager runs execute each bound case inside its template. In the generated file only arguments reach the case, by name; a template variable does not — state the template sets up for the cases goes through global variables (xaml/xaml-editing-catalog.md § Global Variables).
Test Automation Framework
The Official Test Automation Framework template (uip rpa templates search --query "Test Automation Framework") is the starting point for a test project, as the REFramework is for a transactional process; it ships Windows and cross-platform variants in both expression languages. Its execution template runs every bound case inside one root TryCatch:
- Try — a coded initializer loads the project's configuration files into one
Configdictionary (a global variable), the run's test name is added to it, then a Timeout Scope bounded by the test-timeout setting runs the setup hook and the case. - Catch — any exception, from the configuration load, the setup hook or the case, is recorded as a failed Verify Expression with its failure screenshot, the finalize step runs with the exception, and the exception is rethrown, so the case fails with evidence.
- Finally — the finalize step runs after a pass. A rethrow from a workflow's root TryCatch skips its Finally (error-handling-guide.md rule 5), which is why the Catch calls the finalize step itself.
The finalize step runs the teardown hook within its own timeout and logs a teardown failure without failing the case. Cleanup such as closing the application goes in the teardown hook, preconditions in the setup hook; a case keeps no failure wrapper and no configuration load of its own.
Configuration. Settings and constants are entries with a text value; assets are entries naming an Orchestrator asset or credential asset, read when the case starts. Entry names are unique across the files, and each entry is read by name from Config (xaml/xaml-editing-catalog.md § Global Variables). The file formats, the reserved and required entries, and the example_ entries to remove or replace before a run are in the scaffolded README.md; read it and the scaffolded files before changing them.
After init, check two things and fix what is missing:
fileInfoCollectionholds the template's two template entries (ExecutionTemplate,TestCase) and the sample case bound to the execution template, as the template package's ownproject.jsonlists them, each case with a freshtestCaseId(§ project.json Registration).- Every coded file's namespace is the project's (coded/operations-guide.md): a coded file in another namespace does not find the project's generated
CodedWorkflowbase class (CS0246), which per-filevalidatereports.
Execution Template Structure
MyProject/
├── .templates/
│ ├── StagingEnvironment.xaml ← sets environment-specific variables
│ └── ProductionEnvironment.xaml ← different config for prod
├── TestCases/
│ └── TestInvoiceProcessing.xaml ← generic test, environment-agnostic
└── project.json
Key Rules
- Name matching is exact — argument/variable names in the template must match the test case exactly (case-sensitive) for linking to work
- Templates do not execute independently — they only run when associated with a test case
- One template per execution — a test case runs with one execution template at a time; select it in Test Explorer before running
- Template arguments override test case defaults — use this to inject environment-specific values (URLs, credentials, timeouts)
What NOT to Do with Execution Templates
- Do NOT put a case's own checks in an execution template — the template's assertion records exceptions only
- Do NOT create templates with arguments that do not match any test case — they will be ignored
- Do NOT rely on execution templates for data-driven testing — use data sources (variations, Data Service, Queues) instead
Mock Testing (XAML Only) — WIP
This section is a work in progress. Full agent support for mock testing requires a CLI command to create mock copies of workflows (e.g.,
uip rpa create-mock --file-path <WORKFLOW> --project-dir <DIR>). Until that command exists, the agent can generate the test case XAML but cannot reliably create mock files programmatically.
Mock testing replaces selected activities or entire invoked workflows with lightweight stand-ins during a test run, isolating the code under test from side effects (database writes, API calls, UI interactions).
Coded test cases have no built-in mock framework. There is no coded equivalent. To isolate dependencies in coded tests, design workflows with injectable parameters or test individual workflows in isolation.
How Mocking Works
- The test case's When container invokes a mock copy instead of the original workflow
- The mock copy lives at
Mocks/<workflow>_mock.xaml(mirrors source folder structure) - Inside the mock, specific activities are replaced with stand-ins that return predefined values
- At runtime, mocked activities skip their real logic and return the configured test data
Test Case with Mock — XAML Structure
<!-- When container invokes the mock copy instead of the original -->
<Sequence DisplayName="... When">
<ui:InvokeWorkflowFile
DisplayName="Main_mock - Invoke Workflow File (Mocks\Main_mock.xaml)"
WorkflowFileName="Mocks\Main_mock.xaml"
UnSafe="False">
<ui:InvokeWorkflowFile.Arguments>
<scg:Dictionary x:TypeArguments="x:String, Argument" />
</ui:InvokeWorkflowFile.Arguments>
</ui:InvokeWorkflowFile>
</Sequence>
Mocks Folder Structure
MyProject/
├── Main.xaml ← original workflow
├── Mocks/
│ └── Main_mock.xaml ← mock copy of Main.xaml
├── TestCase.xaml ← test case invoking Mocks\Main_mock.xaml
├── TestCaseNoMock.xaml ← test case invoking Main.xaml directly
└── project.json
For workflows in subdirectories, the Mocks folder mirrors the source path:
MyProject/
├── Workflows/
│ └── ProcessInvoice.xaml
├── Mocks/
│ └── Workflows/
│ └── ProcessInvoice_mock.xaml
Mock File Behavior
- Auto-sync: Changes to the source workflow are applied to the mock file when the project is saved in Studio
- Edit scope: In mock files opened in Studio, only mocked activities are editable — non-mocked activities are read-only
- Multiple mocks: You can have multiple mock files for the same workflow (different test scenarios)
What the Agent Cannot Do Yet
- Create mock files — there is no
uip rpa create-mockCLI command. The mock file must be created via Studio's "Create Test Case" dialog with the "Mock workflow under test" checkbox, or manually copied (but Studio manages internal mock metadata that a raw file copy may miss). - Surround with Mock — wrapping individual activities in mock containers is a Studio GUI action. The agent cannot replicate this in XAML without the internal mock activity schema.
Constraints
- Process projects only — mocking is NOT available in Test Automation (
Tests) projects - XAML only — no mock framework for coded test cases
- When container only — mock invocations go inside the
"... When"Sequence - No nested mocks — a mock container cannot be nested inside another mock container
- Package dependency — requires
UiPath.Testing.Activitiesinstalled
Open this reference as its own page
Trigger Pattern Guide
Authoring and editing trigger workflows in XAML. Covers placement, lifecycle, ui:TriggerScope handling, and verification.
Two Trigger Types
uip rpa activities find returns isTrigger and triggerType on every trigger activity. triggerType is the type discriminator.
Integration triggers (triggerType: "integration") — strict placement
- MUST be the first activity of
Main.xaml's rootSequence. - CANNOT be placed inside
ui:TriggerScope. - Connection asset: required for IS-based triggers (Mail, GSuite, O365, Salesforce, Jira, Slack, ServiceNow, any
*.IntegrationService.Activitiespackage). Not required for Orchestrator-native triggers (TimeTrigger,QueueTrigger,ManualTrigger). - Runtime behavior: the activity is an unwrap routine. Orchestrator (or the IS webhook layer) holds the subscription, dispatches a fresh job per event, and injects event payload context. The activity's
Executereads that context — e.g.,NewEmailReceived.ExecuteWithRetryAsyncreadsUiPathEventObjectId, then callsGraphServiceClient.GetEmailByIdAsync(...)to fetch the email. It does not poll, watch, or listen. - Examples:
NewEmailReceived(O365 Outlook, GSuite Gmail),NewFileCreated,NewEventCreated,NewEventInvitationReceived,RowAddedToSheetBottom, SharePoint list-item triggers, every IS connector trigger (Salesforce / Jira / Slack / ServiceNow / Microsoft Teams CRUD events),TimeTrigger,QueueTrigger,ManualTrigger.
Local triggers (triggerType: "local") — flexible placement
- Place EITHER:
- As the first activity of
Main.xaml's rootSequence→ Orchestrator dispatches a fresh job per event (entry-point semantics). - Inside
<ui:TriggerScope.Triggers>, handler in<ui:TriggerScope.Action>→ the robot stays alive while the scope is active; the trigger fires in-process.
- As the first activity of
- The placement choice is a runtime-model decision (per-event jobs vs long-running robot). Both are valid.
- Connection asset: not required.
- Runtime behavior: the activity is a real in-process subscriber.
StartMonitorinstalls the listener (e.g.FileChangeTriggerV3→FileSystemWatcher+ a background event-loopTaskinUiPath.Core.Activities.FileWatcher); events flow throughTriggerScope's bookmark queue when wrapped, or through entry-point dispatch when placed at root. - Examples:
FileChangeTriggerV3,RepeatTrigger,GlobalVariableChangedTrigger, UIA Next triggers (NClickTrigger,NKeyboardTrigger), classic UIA V2 triggers (ClickTriggerV2,ClickImageTriggerV2,KeyPressTriggerV2,ElementStateChangeTrigger,ElementAttributeChangeTrigger,MouseTriggerV2,HotkeyTriggerV2,SystemTriggerV2,SapSessionTrigger),AppRequestTrigger.
Integration triggers never go inside ui:TriggerScope. Local triggers have no equivalent restriction — both placements are valid.
Decision Rule
- Run
uip rpa activities find --query "<event keyword>" --output json. ReadisTriggerandtriggerType. - Branch on the CLI signal:
- Both fields absent → regular activity, not a trigger.
isTrigger: true,triggerType: "integration"→ integration trigger. Place as the first activity of rootSequence; never insideui:TriggerScope. Check connection requirement — IS-based packages (Mail/GSuite/O365/*.IntegrationService.Activities) need aConnectionId;TimeTrigger/QueueTrigger/ManualTriggerdo not.isTrigger: true,triggerType: "local"→ local trigger. Choose placement based on runtime model — first activity of root for per-event dispatch, inside<ui:TriggerScope.Triggers>for long-running in-process subscription. No connection asset.isTrigger: true, unknowntriggerType→ unknown category (forward-compat — new flavors may appear). Read the bundled doc and ask the user if still ambiguous.
- For trigger activities, read both docs (per SKILL.md Rule 21): the bundled
references/activity-docs/<packageName>/<closest-version>/activities/<ClassNameTail>.mdand the project-local{PROJECT_DIR}/.local/docs/packages/<packageName>/activities/<ClassNameTail>.mdif present. The bundled doc carries placement guidance, deployment context, and cross-cutting namespace/assembly gotchas the auto-generated.local/docsextractor omits; the.local/docsversion reflects the exact installed package version. Also read the package's bundledoverview.md.
Entry-Point Worked Example — Office 365 New Email Received
A workflow that fires when an Outlook email arrives in INBOX with attachments.
<Activity mc:Ignorable="sap sap2010" x:Class="Main"
xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:sap="http://schemas.microsoft.com/netfx/2009/xaml/activities/presentation"
xmlns:sap2010="http://schemas.microsoft.com/netfx/2010/xaml/activities/presentation"
xmlns:sco="clr-namespace:System.Collections.ObjectModel;assembly=System.Private.CoreLib"
xmlns:ui="http://schemas.uipath.com/workflow/activities"
xmlns:umamt="clr-namespace:UiPath.MicrosoftOffice365.Activities.Mail.Triggers;assembly=UiPath.MicrosoftOffice365.Activities"
xmlns:umm="clr-namespace:UiPath.MicrosoftOffice365.Models;assembly=UiPath.MicrosoftOffice365"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Sequence DisplayName="Main Sequence">
<Sequence.Variables>
<Variable x:TypeArguments="umm:Office365Message" Name="email" />
</Sequence.Variables>
<umamt:NewEmailReceived
DisplayName="New Email Received"
ConnectionId="<CONNECTION_GUID>"
UseConnectionService="True"
AuthScopesInvalid="False"
BrowserFolderId="INBOX"
BrowserFolderName="Inbox"
FilterExpression="(parentFolderId=='INBOX')&&(hasAttachments==`true`)"
IncludeAttachments="True"
MarkAsRead="True"
WithAttachmentsOnly="True"
Result="[email]" />
<!-- Handler: rest of the Sequence acts on `email` -->
<ui:LogMessage Level="Info" Message="["Got email from " + email.From.Address]" />
</Sequence>
</Activity>
Three critical shape rules:
- The trigger is the first child of the root
Sequence. There is noui:TriggerScopewrapping it. Result="[email]"binds the activity'sOffice365Messageoutput to a workflow-scope variable. The rest of theSequenceis the handler.FilterExpressionruns server-side (free) before the trigger fires — never re-implement the filter as anIfinside the handler. Boolean literals use backticks; AND uses XML-escaped&&. Full syntax: activity-docs/UiPath.MicrosoftOffice365.Activities/3.8/activities/NewEmailReceived.md.
Local Trigger Worked Example — UI Click
A workflow that runs while a desktop app is open and reacts to clicks. The exact xmlns prefix and args type vary by package — always start from uip rpa activities get-default-xaml --activity-class-name <FullClassName> rather than hand-writing the namespace.
Structural shape (placeholders in angle brackets — fill from get-default-xaml):
<Activity x:Class="Main" ...>
<Sequence DisplayName="Main Sequence">
<ui:TriggerScope DisplayName="Trigger Scope"
SchedulingMode="Sequential"
xmlns:ui="http://schemas.uipath.com/workflow/activities">
<ui:TriggerScope.Triggers>
<!-- One or more local trigger activities. Get full XAML via:
uip rpa activities get-default-xaml \
--activity-class-name <FullClassName> \
--project-dir "<PROJECT_DIR>" --output json -->
<<TriggerPrefix>:<TriggerClassName> DisplayName="..." ... />
</ui:TriggerScope.Triggers>
<ui:TriggerScope.Action>
<ActivityAction x:TypeArguments="<TriggerArgsType>">
<Sequence>
<!-- handler -->
</Sequence>
</ActivityAction>
</ui:TriggerScope.Action>
</ui:TriggerScope>
</Sequence>
</Activity>
Shape rules:
ui:TriggerScope(UiPath.Core.Activities.TriggerScope, in packageUiPath.System.Activities) is the container.Triggersis a collection — one or more child trigger activities.ui:TriggerScope.Actionis the handler. It is anActivityActiontyped on the trigger's args type (e.g.MonitorClickEventArgsforNClickTrigger,FileSystemArgsfor file-change variants). Useget-default-xamlon the trigger to discover the exact args type.SchedulingModecontrols handler queueing (source:Triggers/TriggerScope.cs):Concurrent— fire all handler instances in parallel.Sequential(default in most templates) — queue events; run one handler at a time in arrival order. Filterable triggers can drop duplicate queued events.SequentialCollapse— sequential, but collapse repeated events to the latest.SequentialDrop— sequential, but cancel the running handler when a new event arrives.OneTime— fire once and cancel the scope's child triggers.
ContinueOnError— whentrue, a faulted handler logs and the scope keeps running. Whenfalse(default), a fault stops the scope.Breakactivity (fromUiPath.System.Activities) inside the handler exits theTriggerScopecleanly.- The job remains alive for as long as
TriggerScopeis active. This is the wrong choice for events that arrive over hours/days; place the trigger at the workflow root instead, so Orchestrator owns the subscription and dispatches per event.
Reading and Editing Existing TriggerScope XAML
Existing projects routinely use ui:TriggerScope. When you encounter one, treat it as a valid local-trigger pattern — do not flatten it. The choice between scoped and root placement for a local trigger is a runtime-model decision (long-running robot vs per-event jobs); changing it without the user's intent is wrong.
How to identify: any XAML containing <ui:TriggerScope ...> is a local-trigger workflow. The robot is expected to stay alive while this scope is active.
Safe edits:
- Adding another local trigger to the same scope → append to
<ui:TriggerScope.Triggers>. Confirm the new trigger's args type matches (or the scope'sActionx:TypeArgumentsis the common base — typicallyTriggerArgs). Integration triggers cannot be added here. - Modifying the handler → edit inside
<ui:TriggerScope.Action>. Do not move handler activities outside the scope. - Changing
SchedulingMode→ safe; pick from the values above. Default unset value behaves asSequential.
Unsafe edits — these break the workflow:
- Moving a local trigger out of
ui:TriggerScopeto root placement when the user only asked you to "modernize" the workflow. The two placements have different deployment models (per-event jobs vs long-running robot); ask the user first. - Removing
<ui:TriggerScope.Triggers>while keeping<ui:TriggerScope.Action>—CacheMetadatavalidation fails (TriggerScope_NoTrigger). - Inserting an integration trigger (
triggerType: "integration") inside<ui:TriggerScope.Triggers>— see Anti-patterns.
When to question a TriggerScope you find: if <ui:TriggerScope.Triggers> contains an activity whose bundled doc labels it Integration trigger (e.g. NewEmailReceived, TimeTrigger, QueueTrigger), the prior author placed an integration trigger inside a TriggerScope. The workflow compiles but does not get registered as an Orchestrator trigger. Flag this to the user — the fix is to move that trigger to the workflow root.
Catalog of Trigger Activities
Integration (root placement, never inside ui:TriggerScope)
Every activity whose bundled doc labels it Integration trigger, plus every Integration Service connector trigger (its namespace will contain .Triggers). The bundled hand-written docs cover these:
| Package | Activity | Bundled doc |
|---|---|---|
UiPath.System.Activities |
TimeTrigger (Time Trigger) |
activity-docs/UiPath.System.Activities/26.4/activities/TimeTrigger.md |
UiPath.System.Activities |
QueueTrigger (New Item Added to Queue) |
activity-docs/UiPath.System.Activities/26.4/activities/QueueTrigger.md |
UiPath.System.Activities |
ManualTrigger (Manual Trigger) |
activity-docs/UiPath.System.Activities/26.4/activities/RuntimeContext.md |
UiPath.MicrosoftOffice365.Activities |
NewEmailReceived |
activity-docs/UiPath.MicrosoftOffice365.Activities/3.8/activities/NewEmailReceived.md |
UiPath.GSuite.Activities |
NewEmailReceived (Gmail), NewFileCreated, NewEventCreated, NewEventInvitationReceived, RowAddedToSheetBottom |
activity-docs/UiPath.GSuite.Activities/3.8/activities/ |
Beyond the bundled set: every Integration Service connector trigger qualifies — Salesforce CREATED/UPDATED/DELETED, Jira issue triggers, ServiceNow record triggers, Slack message triggers, Microsoft Teams triggers, SharePoint list-item triggers, etc. For IS trigger semantics (eventMode, webhook URL retrieval, filter trees), query the CLI: uip is activities list "<connector-key>" --triggers --output json and uip is triggers describe "<connector-key>" "<OPERATION>" "<object>" --output json.
Local (flexible placement — first activity of root, or wrapped in <ui:TriggerScope.Triggers>)
Concrete authorable activities. Listed by package. For full property surface, run uip rpa activities get-default-xaml --activity-class-name <FullClassName> — namespaces and args types vary.
| Package | Concrete activities | Notes |
|---|---|---|
UiPath.System.Activities |
RepeatTrigger, GlobalVariableChangedTrigger, FileChangeTriggerV3 |
Interval, global-variable change, filesystem watcher. |
UiPath.UIAutomationNext.Activities |
NClickTrigger, NKeyboardTrigger |
UIA Next click and keyboard events. Args types: MonitorClickEventArgs, MonitorKeyboardEventArgs. Both derive from UIA Next's TriggerBase<T> → Platform.InterruptibleTriggerBase<T>. |
UiPath.UIAutomation.Activities (Classic V2) |
Selector-bound: ClickTriggerV2, ClickImageTriggerV2, KeyPressTriggerV2, ElementStateChangeTrigger, ElementAttributeChangeTrigger. System-level: MouseTriggerV2, HotkeyTriggerV2, SystemTriggerV2, SapSessionTrigger. |
All share EventInfoTriggerArgs. Selector-bound triggers require a target descriptor; system-level triggers monitor process-wide events. SelectorTriggerActivityV2 and MouseAndKeyTriggerActivityBase are abstract bases — not directly authorable. |
UiPath.WorkflowEvents.Activities |
AppRequestTrigger |
Cross-workflow request bus inside a running job. |
If the activity is not in this table: run uip rpa activities find --query Trigger against the installed package and read triggerType. "local" activities can be placed at root or wrapped in TriggerScope — choose per runtime model.
Connection Handling (IS Triggers)
Integration triggers from Integration Service packages require a ConnectionId. A placeholder GUID (00000000-0000-0000-0000-000000000000) passes uip rpa validate and uip rpa build but fails at runtime when Orchestrator tries to subscribe. Resolve a real connection scoped to the connector and across all folders (active-folder-only scans miss connections owned by other folders):
uip is connections list "<connector-key>" --all-folders --output json
For example, uip is connections list "uipath-microsoft-outlook365" --all-folders --output json for the O365 Mail triggers. Copy the connection's GUID into ConnectionId. If no connection exists, create one (uip is connections create <connector-key>) and verify it's active (uip is connections ping <connection-id>).
Server-Side Filtering
Integration triggers from IS packages typically expose a filter property — an OData-style boolean predicate (or structured tree) that runs on the connector side before the trigger fires. Use it for any "fire only if X" logic. Re-implementing the filter inside the handler wastes Orchestrator dispatch and robot time on events you would discard.
Per-package conventions (read each package's bundled overview.md for canonical syntax):
- O365 Mail (
umm:prefix family):FilterExpressionas a string attribute. OData-like:(parentFolderId=='INBOX'),(hasAttachments==true). AND uses&&; booleans use backticks. See activity-docs/UiPath.MicrosoftOffice365.Activities/3.8/activities/overview.md. - GSuite Gmail:
Filteras a structured child element withLogicalOperator+Criterialeaves, not a string. See activity-docs/UiPath.GSuite.Activities/3.8/activities/NewEmailReceived.md. - IS connector triggers (Salesforce, Jira, Slack, …): authored as a structured filter tree, not a string. Discover the filterable field names via
uip is triggers describe "<connector>" "<OPERATION>" "<object>" --output json→ readData.FilterFields[*].Name. The CLI compiles the tree into the runtime expression; do not pass the compiled form directly.
Lifecycle and Verification
Lifecycle depends on placement, not type. Two paths:
Entry-point lifecycle (trigger at workflow root)
Applies to all integration triggers, and to local triggers placed at root.
- Author — place trigger as the first activity of root
Sequence, bind output to variable, write handler. Per-filevalidateclean. - Build —
uip rpa build "<PROJECT_DIR>" --output jsonclean. - Publish —
.nupkgto Orchestrator (see cli-reference.md § Pack & Publish to Orchestrator). On publish, Orchestrator detects the trigger from the workflow's activity registration and exposes it as a Process/Time/Queue Trigger candidate.
uip rpa run is NOT a meaningful smoke test for entry-point triggers. The CLI executes the workflow once in-process, which does not exercise Orchestrator subscription or the connector's webhook/polling lifecycle. A clean run only proves the handler XAML compiles and the trigger activity can be instantiated.
In-process lifecycle (local trigger inside ui:TriggerScope)
Applies only to local triggers wrapped in ui:TriggerScope.
- Author —
ui:TriggerScopewithTriggers(one or more local trigger activities) andAction(the handler). Per-filevalidateclean. - Build —
uip rpa buildclean. - Run —
uip rpa run --file-path Main.xaml --project-dir "<PROJECT_DIR>" --output json. The robot stays alive; trigger events fire while the run is active. Generate an event (click, file change, etc.) and confirm the handler executes. - Deploy — publish to Orchestrator and start as a long-running attended/unattended job. The job remains active and consumes a robot slot for the duration.
Anti-patterns
- Integration trigger wrapped in
ui:TriggerScope. Re-author by removing theui:TriggerScopewrapper and placing the trigger at the root. - Re-implementing the filter as an
Ifin the handler. Robot pays dispatch cost on every event the filter would have rejected. Move the predicate into the trigger's filter property. - Calling
uip rpa runto "test" an O365/Gmail/Salesforce/queue/schedule trigger. See entry-point lifecycle above —rundoes not exercise Orchestrator subscription. - Moving a local trigger out of
ui:TriggerScopeto root placement without intent. Both placements are valid for local triggers; the choice is a runtime-model decision (per-event jobs vs long-running robot). Confirm with the user before changing it. - Hand-editing the auto-generated
.local/docs/.../<Trigger>.md. That file is regenerated on package restore. Treat it as read-only; the bundled doc inreferences/activity-docs/is the editable source of placement and example guidance. - Inventing an
xmlns:prefix for an unfamiliar trigger. Always pull the namespace fromuip rpa activities get-default-xaml --activity-class-name <FullClassName>; do not infer it from the class's logical hierarchy.
Open this reference as its own page
UIA Policies Catalog
This skill's conditional UIA policies, one entry each. Read by entry, never end-to-end: Grep ^## , then Read the entry whose condition holds, through the next ## heading.
| Entry | Read when |
|---|---|
| § Running UI Automation Workflows (with its profiling and selector-recovery subsections) | before the first run or debug of a UIA workflow, and at a runtime selector failure |
| § Placeholder-Selector Stub Pattern | a workflow must ship WITHOUT live app access: app not installed, no GUI, capture deferred, or the UIA package cannot be installed (Rule 7a fallback); a migration's recorded targets are not stubs (Rule 7) |
| § Object Repository as a Published UI Library | the task publishes or consumes shared Object Repository descriptors |
Running UI Automation Workflows
Always use uip rpa debug start (not uip rpa run) when running workflows with UI automation. A debug session pauses on error instead of tearing down the application, leaving the UI state available for inspection. The command returns as soon as that happens — DebugState: "Suspended" with the exception and locals in DebugDetails — so act on the response instead of waiting for the run to end (see debugging.md § The stable-state debug loop).
Every debug run must follow this procedure to prevent stale windows from accumulating or being reused in a dirty state:
- Record the window baseline — list top-level windows via the UIA snapshot CLI and note which w-refs and titles are already present. Procedure: the package guide's § Window Baseline (
{PROJECT_DIR}/.local/docs/packages/UiPath.UIAutomation.Activities/ui-automation-guide.md). - Run the workflow — no
--output-filter; the envelope is the verdict, and the workflow's ownLog Messageoutput streams above it (Helm) or sits inData.logEntries(Studio Desktop) — shapes and verdict rules in cli-reference.md § Capturing the verdict:
Auip rpa debug start --file-path "<FILE>" --project-dir "<PROJECT_DIR>" --skip-build --output jsonSuspendedon a fault that a Try Catch or Retry Scope of the workflow handles is not a failure: continue it (debugging.md § The stable-state debug loop). If the run fails, follow Runtime Selector Failure Recovery — this is the only correct recovery path. Do not hand-edit selectors in the XAML file. - When done (success or failure) — cancel the debug session:
uip rpa execution cancel --project-dir "<PROJECT_DIR>" --output json - List windows again via the UIA snapshot CLI.
- Diff before vs after, in this order:
- Reset apps the run drove. A faulted or cancelled run can leave any app it drove — leaked or in the baseline — mid-task: unsaved edits, an open dialog, menu or prompt, a half-filled form, a screen other than the one the workflow starts from. Inspect each such window via the UIA snapshot CLI and return it to its pre-run state via the
uip rpa uia interactCLI. Choose the action that discards the run's changes (cancel, close without saving, navigate back) — never one that commits them (save, submit, confirm). A dismiss or close can raise a prompt the run never captured: capture it before answering. Reset before closing any window: closing a window does not discard its state, and session-restoring apps reopen unsaved content at the next launch. Leave state already present in the baseline — it is the user's. - Close leaked windows. Any window present now that was NOT in the baseline was opened by the workflow. Close each such window via the
uip rpa uia interactCLI (diff and close procedure: the package guide's § Window Baseline).
- Reset apps the run drove. A faulted or cancelled run can leave any app it drove — leaked or in the baseline — mid-task: unsaved edits, an open dialog, menu or prompt, a half-filled form, a screen other than the one the workflow starts from. Inspect each such window via the UIA snapshot CLI and return it to its pre-run state via the
Skipping steps 4-5 causes the next run's open-if-not-open behavior to reuse a stale window in whatever state it was left in, or -- if the selector doesn't match -- to spawn a duplicate instance.
Advanced Debugging — Profiling
For advanced debugging, add --profiling to collect insightful per-activity execution data, timings, and before- and after-execution screenshots:
uip rpa debug start --file-path "<FILE>" --project-dir "<PROJECT_DIR>" --skip-build --output json --profiling
Use the before-execution screenshot to confirm the application/element started in the correct state, and the after-execution one to validate the expected outcome. Each screenshot's filename is recorded in the run's .uistat file; the image sits in the Screenshots folder in the same directory as that .uistat file. See debugging.md § Profiling Workflow Performance for details.
Runtime Selector Failure Recovery
"UI element not found", "UI element is invalid", element not on screen -- these surface at runtime, not during static validation. They occur when a selector was captured against one app state but the DOM changed by the time the activity executes.
When a workflow fails at runtime with a selector error:
- The app is already in the right state. The debug session paused at the failing activity, so the app's current DOM reflects the state that activity needs to target.
- Identify the failing element -- read the error to find which descriptor/element failed.
- Read the window selector -- from the Object Repository files, find the screen's selector that scopes the failing element.
- Follow the package's recover selector guide -- routed from
ui-automation-guide.md§ Documentation. - Clean up and re-run -- follow the procedure above (stop, diff, reset app state, close leaked windows, re-run).
Repeat until the workflow completes successfully. Each failure advances the app to the next problematic state, making recovery self-correcting.
Recovery circuit breaker — two attempts per element. When the SAME element fails at runtime after two recovery cycles, do not run a third: elements that keep failing recovery typically remount (dialogs, popups, re-rendered panes), and selector hardening cannot converge on them. Re-route that one element instead: re-run the capture flow for it with the CV/semantic fallback enabled (the capture flow's fallback chain owns the mechanics), re-link, and continue the run loop. Count attempts per element, not per run — three failures of one element across runs is the same signal.
Placeholder-Selector Stub Pattern
Sometimes you must generate a UI automation workflow without live app access — the app is not installed on the build machine, the agent has no GUI, the user has explicitly deferred target capture to a developer who will run Indicate later, or the UIA package cannot be installed (Rule 7a). In that case, the workflow ships with placeholder selectors. The pattern below is the only acceptable shape, except in a migration (§ When the rule does NOT apply). It requires no UIA package or CLI — that is the point.
Rule
When live capture is unavailable, write the real UIA activity (XAML <NApplicationCard> / <NTypeInto> / <NClick> / <NGetText> / etc., or coded uiAutomation.Open / Attach / TypeInto / Click) with the target descriptor's selector left as a placeholder and a TODO Indicate marker embedded in the activity's DisplayName (XAML) or in a // TODO[Indicate] comment immediately adjacent to the call (coded).
Do NOT replace the activity itself with a Log call.
Why this matters
A Log("LoginWorkflow: type username") stub:
- Passes
uip rpa validate(no UIA activity, no selectors to validate). - Passes
uip rpa build(just a string in a Log activity). - Runs cleanly via
uip rpa run(the Log activity emits a message). - Does nothing. The workflow looks complete to the validator, looks complete to a CI smoke test, and silently fails to perform the actual automation.
A real <uix:NTypeInto> activity with placeholder selector + TODO Indicate marker:
- Build/validate surface the unconfigured targets ("Target or Input UI Element must be set" — hard errors in current packages) — useful, since they tell the developer what is left to do. A stub-mode deliverable therefore does NOT reach a clean
build; its acceptance bar is that the ONLY remaining validate/build errors are the expected unconfigured-target ones. - The activity is wired into the workflow's control flow, package dependencies, scope, and Object Repository registration plumbing. The developer's only remaining work is Indicate.
- The TODO marker is visible in Studio's designer pane and grep-able in the file.
- The cost of "what does this stub actually need from the developer?" drops from "read this carefully and infer" to "click Indicate on the marked activities."
XAML example
<uix:NApplicationCard ApplicationWindow="{x:Null}"
DisplayName="TODO Indicate — Use Application/Browser (ACME WI app)"
sap2010:WorkflowViewState.IdRef="NApplicationCard_1">
<uix:NApplicationCard.Body>
<Sequence sap2010:WorkflowViewState.IdRef="Sequence_1">
<Sequence.Variables>
<Variable x:TypeArguments="x:String" Name="username" />
<Variable x:TypeArguments="ss:SecureString" Name="password" />
</Sequence.Variables>
<ui:GetRobotCredential DisplayName="Get ACME WI credential"
AssetName="[in_CredentialAssetName]"
Username="[username]"
Password="[password]"
sap2010:WorkflowViewState.IdRef="GetRobotCredential_1" />
<uix:NTypeInto DisplayName="TODO Indicate — Type Username"
Text="[username]"
sap2010:WorkflowViewState.IdRef="NTypeInto_1" />
<uix:NTypeInto DisplayName="TODO Indicate — Type Password"
SecureText="[password]"
sap2010:WorkflowViewState.IdRef="NTypeInto_2" />
<uix:NClick DisplayName="TODO Indicate — Click Login"
sap2010:WorkflowViewState.IdRef="NClick_1" />
<uix:NGetText DisplayName="TODO Indicate — Read WIID field"
Text="[out_WIID]"
sap2010:WorkflowViewState.IdRef="NGetText_1" />
</Sequence>
</uix:NApplicationCard.Body>
</uix:NApplicationCard>
What this gives the developer:
NApplicationCardis in the right place (entry point of the screen).- Three
NTypeInto/NClick/NGetTextare wired into the Sequence in the right order. - The credential is read inside the card from the asset name the workflow receives (SKILL.md Common Rule 5a);
Text,SecureTextand theNGetTextoutput are bound to the right variables. - Each activity's
DisplayNameisTODO Indicate — <human description>. Studio shows this on the canvas; the developer clicks each and runs Indicate. - Once Indicate is run,
DisplayNameis updated,Targetbecomes a real descriptor, and the workflow is shippable.
What you must NOT do:
<!-- WRONG: replaces the actual activity with a log stub -->
<ui:LogMessage Message="LoginWorkflow: type username" Level="Info" />
<!-- TODO[selectors]: replace this with an actual TypeInto activity once capture is done -->
That XAML compiles, validates, runs — and does nothing. A re-run of the build pipeline at a later date silently ships the same broken automation.
Coded example
[Workflow]
public string Execute(string credentialAssetName)
{
// TODO[Indicate]: attach to the ACME WI app — replace placeholder with Descriptors.<App>.<Screen>
using var app = uiAutomation.Open(/* TODO[Indicate]: Descriptors.AcmeWi.Login */);
var (username, password) = system.GetCredential(credentialAssetName);
// TODO[Indicate]: target the Username field
app.TypeInto(/* TODO[Indicate]: Descriptors.AcmeWi.Login.Username */ "username-placeholder", username);
// TODO[Indicate]: target the Password field
app.TypeInto(/* TODO[Indicate]: Descriptors.AcmeWi.Login.Password */ "password-placeholder", password);
// TODO[Indicate]: target the Login button
app.Click(/* TODO[Indicate]: Descriptors.AcmeWi.Login.LoginButton */ "login-button-placeholder");
// TODO[Indicate]: target the WIID readout field on the next screen
using var home = uiAutomation.Attach(/* TODO[Indicate]: Descriptors.AcmeWi.Home */);
return home.GetText(/* TODO[Indicate]: Descriptors.AcmeWi.Home.WIIDField */ "wiid-field-placeholder");
}
What this gives the developer:
- The actual
uiAutomation.Open/Attach/TypeInto/Click/GetTextcalls are in the right order with the right argument bindings. - Every
TODO[Indicate]marker tells the developer the exact descriptor to wire up. - The placeholder string argument lets the project build and
uip rpa packages inspectsucceed; once Indicate runs andDescriptors.<App>.<Screen>.<Element>exists, replace the placeholder string with the descriptor reference.
What you must NOT do:
[Workflow]
public string Execute(string credentialAssetName)
{
// TODO[selectors]: replace these with real uiAutomation calls once Object Repository is populated
Log("LoginWorkflow: type username");
Log("LoginWorkflow: type password");
Log("LoginWorkflow: click Login");
Log("LoginWorkflow: read WIID");
return "";
}
This compiles, validates, runs, and does nothing. It is the most expensive kind of stub.
When the rule does NOT apply
- Live capture is available. Run
uia-configure-target/ Indicate first; the workflow ships with real descriptors. No stub pattern needed. - A migration translates the source's recorded targets.
- The activity is not UI. Logging is fine for actual logging steps (e.g., "Log the transaction ID before processing"). The rule applies only to UI-interaction steps that, in a finished workflow, would be
NTypeInto/NClick/NGetText/ etc.
Acceptance check
Before declaring a stub-mode workflow done, re-read every UI-interaction step in the PDD / SDD and confirm that the workflow contains a real UIA activity (XAML element or coded uiAutomation.* call) for each one — not a Log call. Grep for Log\( and LogMessage inside the workflow body; for every match, verify it represents an actual logging step, not a substitute for a UI action.
Object Repository as a Published UI Library
Selector breakage is the #1 maintenance cost in UI automation. A UI Library is a published library project whose Object Repository ships inside the .nupkg — descriptors defined once, consumed by every automation against the same application. Fix a descriptor once, bump the version, and all consumers inherit the fix.
Hierarchy and naming
Application (InvoicePortal)
└── Screen (LoginPage)
└── Element (UsernameField)
- Reference form:
App.Screen.Element—InvoicePortal.LoginPage.UsernameField - Business-meaningful PascalCase element names:
SubmitOrderButton, notButton32 - One descriptor per distinct UI element; screens mirror the application's logical screens
Extract-and-publish pattern
Precondition: the source project has captured descriptors (.objects/ content). If it has none, capture targets first (the package guide's § Configuring Targets) — there is nothing to promote, and hand-writing descriptors is forbidden.
- Develop the first process against its local Object Repository, configuring targets as usual (§ Configuring Targets in the package guide).
- Promote the reusable descriptors into a dedicated UI Library project — a library project (library-authoring-guide.md) holding the shared Object Repository; pack and publish per library-authoring-guide.md § Pack & Publish. Concrete Object Repository manipulation steps: the package's Object Repository reference (routed from the package guide § Documentation).
- One UI Library per corporate application (SAP, Salesforce, Workday) — an update to one app's selectors must not force re-deployment of another's.
- New automations against that application consume the UI Library from the start. Process-specific one-off descriptors stay in the local Object Repository.
Consumption
Install the UI Library as a package dependency; its descriptors appear under UI Libraries in the Object Repository and are targetable like local descriptors. Coded workflows resolve them via the package guide's § Finding Descriptors Step 2 (UILibrary NuGet packages). Selector updates propagate by bumping the dependency version — no per-workflow changes.
Update rules — MANDATORY
- Update descriptors in place — NEVER delete-and-re-add an element. The element-to-activity link is identity-based; deleting the element severs it and every consumer activity bound to it breaks, even if a same-named element is re-created.
- Version by SemVer (library-authoring-guide.md § Versioning): selector fix without renaming = patch; element/screen rename or restructure = breaking = major.
- Promote accepted healing fixes. When a selector recovery (§ Runtime Selector Failure Recovery) is accepted in a workflow that consumes a shared UI Library, apply the fix in the UI Library and bump the version — do not re-fix the same selector consumer by consumer.
Open this reference as its own page
UIA Starter Guide
Read this file in full before any UI-automation work (Rule 7). Then:
- Verify prerequisites — minimum package version: § UIA Prerequisites below. If the package cannot be installed, use uia-policies-catalog.md § Placeholder-Selector Stub Pattern.
- Read the UIA package's core guide IN FULL —
{PROJECT_DIR}/.local/docs/packages/UiPath.UIAutomation.Activities/ui-automation-guide.md. It owns the shared UIA law — window baseline, the mandatory target-generation gate, terminology, common pitfalls, control-specific interaction, reading values — and its § Documentation routes to everything else, including the per-mode authoring guides. Before authoring UIA activities, additionally read your mode's authoring guide IN FULL (XAML or coded, routed from § Documentation) — during capture-only phases neither mode guide is needed yet. The core guide ships with the package: if the package is installed but the file is absent, the installed version predates it — treat as below the minimum version (§ UIA Prerequisites).
Prerequisites are below. The skill's other UIA policies — running and debugging UIA workflows, the deliverable when live capture is unavailable, publishing Object Repository descriptors as a shared UI Library — are entries of uia-policies-catalog.md, each read when its condition holds.
UIA Prerequisites
Required package: UiPath.UIAutomation.Activities — minimum version (<MIN_VERSION>): 26.10.4, a stable release on the official UiPath NuGet feed. The uip rpa uia CLI, the package docs, and the UIA skills require <MIN_VERSION> or newer — before any UIA work, check the installed version in project.json under dependencies. Do not hardcode the version from memory; this section is the only source of truth.
Install or upgrade the package through the version question in SKILL.md § Resolving Packages & Activity Docs, Step 1, offering only versions at or above <MIN_VERSION>.
More in this playbook
Browser mate
Use when automating a real, logged-in Chrome WITHOUT disturbing the user's open tabs — e.g. authenticated sessions like ChatGPT, LinkedIn, or any site needing a persistent login. Launches or reuses a dedicated debug Chrome instance per named profile that coexists with the user's main browser; it never quits or kills any browser (unlike real-browser, which closes Chrome Beta's tabs). Trigger on "automate this site without closing my tabs", "use my logged-in session", "open ChatGPT/LinkedIn in automation", or when a browser task must preserve the user's existing windows. macOS, requires the agent-browser CLI.
RPAMIT Matt Townsend + 1Engineer @ MicrosoftManage desktop flows
Manage and run Power Automate Desktop (RPA) flows and machine groups. Use when the user asks about desktop flows, RPA, or machine groups.
RPAMITUipath architecture deepening
Use only when the user explicitly asks to deepen a proven UiPath architecture hotspot into ranked design options and a safe handoff.

