Polarion Applications

Polarion Applications

Early Access in Polarion 2612

Polarion Applications and the Polarion Application SDK are part of the Early Access Program. The feature is switched off by default, and the API, the manifest format and the details documented here may change in later releases.

To try it, set polarionapp.enabled=true in Global Administration → Configuration Properties, and enable REST API token authentication in polarion.properties. Enable Applications in Polarion · Roadmap

The new way to extend Polarion. Build rich applications with the web technology you know, add your own REST endpoints on the server, package everything as one unit and install it through Administration.

Build your first application What is the framework?

From code to Polarion in minutes

Write it like any web app. Upload it once. Watch it run inside Polarion, from a panel in a work item to a full-page editor on top of the REST API.

  • From code to work item in one loop

    Video: 2:48. Build a form extension with Vite and React, package it, upload it in Administration and see it rendered inside a work item.

  • A navigation topic: the Work Items Grid

    Video: 1:24. A spreadsheet-style editor for work items delivered as an application, with inline editing and batched saves through the REST API.

Where your application appears

  • Form extension

    A panel inside the Work Item form. It knows which work item is open and can read or update it.

    Form extension

  • Sidebar

    A panel next to the Work Items table or a Document. It follows the user's selection in real time.

    Sidebar

  • Navigation topic

    A full page in the project navigation: dashboards, reports, editors.

    Navigation topic

Coming next: widgets for pages and reports, administration views, and packages that also carry scripts and templates. See Upcoming: widgets and administration.

Two ways to work with Polarion data

  • Polarion REST API

    Call the complete, documented REST API directly from your view. The framework supplies the token; you supply the fetch.

    Calling the REST API from a view

  • Your own REST endpoints

    Declare endpoints in the manifest and implement them in JavaScript that runs on the server with the full Polarion Java API.

    Your own REST endpoints

  • Which one when?

    Most things are a REST call away. Endpoints are for logic that must run on the server, with the Java API, or that reads many objects at once.

    REST API or your own endpoints?

Find your way

  • Getting started

    Prerequisites, enabling the feature, and a complete walkthrough from an empty folder to a panel in a work item.

    Prerequisites

  • Examples

    Seven complete applications: from hello world to a release checklist driven by your own endpoints, each with a downloadable package and source.

    Examples

  • Performance and load

    Keep an application light on a shared server: fewer requests, bounded scripts and SQL, tests with realistic data.

    Performance and load

  • Reference

    manifest.json, the SDK API, the context object, the endpoint runtime and the configuration XML.

    manifest.json

Introduction

The extensibility framework

Polarion Applications are the new extensibility framework of Polarion. An application is a self-contained package that adds functionality to Polarion: user interface that appears inside the Polarion UI, and server-side logic exposed as your own REST endpoints. You build it with standard web technology, package it as a ZIP, and an administrator installs it in Global Administration → Applications. No Java plug-in, no server file-system access, no restart.

Polarion 2612 ships the first generation of the framework as a preview. It is the foundation on which the next releases will deliver more: additional places in the UI where applications can appear, and additional kinds of content that an application can carry, such as scripts and templates. Applications are how Polarion is meant to be extended from now on.

What an application is

An application bundles three things:

Part What it is Where it runs
Views Web pages that Polarion shows in defined places of its UI: a panel in the work item form, a sidebar next to a table or document, a page in the project navigation. In the user's browser, inside the Polarion page
Your own REST endpoints HTTP endpoints under your application's URL, implemented as JavaScript that runs on the Polarion server with access to the Polarion Java API. On the Polarion server
Manifest manifest.json: the identity of the application and the list of its views and endpoints. Read by Polarion on upload

Views and endpoints are both optional in principle, but together they are what makes an application rich: the view is the experience, the endpoints are the capability.

Two ways to work with Polarion data

From a view you can reach Polarion data in two ways, and most applications use both:

  1. The Polarion REST API. The complete, documented API of Polarion, called directly from the browser. The application receives an authentication token for the current user from the framework, so there is nothing to configure. Use it for everything it covers: reading and writing work items, documents, test runs, plans, users.
  2. Your own REST endpoints. When the REST API is not enough, you write the endpoint yourself. The script runs on the server, as the current user, with the full Polarion Java API. Aggregate across hundreds of objects in one request, implement rules and validations, talk to external systems with server-side secrets. The framework handles routing, authentication and JSON serialization.

The Polarion REST API and Your own REST endpoints sections cover both in depth. REST API or your own endpoints? helps you decide.

Where applications appear: views

The places in the Polarion UI that accept applications are called view types. Polarion 2612 provides three:

View type Where it appears Typical use
Form extension A panel in the Work Item form, positioned by the administrator in the form layout. Everything that is about the open work item: related data, visualizations, guided editing.
Sidebar The sidebar next to the Work Items table and inside Documents. Follows the user's selection. Inspectors, bulk actions, checks on the selected items.
Navigation topic A full page in the project navigation. Dashboards, reports, editors that need the whole screen.

More view types are planned, among them widgets for pages and reports and administration views. See Upcoming: widgets and administration.

A form extension rendered inside a work item

How a view talks to the framework

The view runs in an iframe inside the Polarion page. A small npm package, the Polarion Application SDK (polarion-app-sdk), connects it to the host: it tells the view which project, work item, document or selection it is embedded in, delivers events such as selection changed, and supplies the base URLs and the token for calling the REST API and your endpoints. See How an application works.

Who this guide is for

This guide assumes you have never seen a Polarion Application before. It expects that you can use a terminal, Node.js and npm, that you can write a small web page in JavaScript or TypeScript (the examples use React and Vite), and that you can log in to a Polarion 2612 server as an administrator or ask one for help with the installation steps. You do not need Java, the Polarion Java SDK, or knowledge of Polarion's internals.

How this differs from older extension options

Option Deployment Language Where it runs
Polarion Application ZIP upload in Administration Web technology + JavaScript endpoints Browser iframe; endpoints on the server
Java plug-in (form extension, widget, servlet) Bundle copied to the server, restart Java Server
Velocity / JavaScript custom panels Configuration XML Velocity, HTML Server-side rendering
External REST client Separate system Any Outside Polarion

Applications combine the reach of a plug-in (inside the UI, with server-side logic) with the deployment model of a web application. They are the recommended path for new extensions.

Where to go next

Introduction

How an application works

This page describes the mechanism behind a Polarion Application. You do not need to understand all of it to build one, but it explains why the manifest, the SDK and the configuration XML look the way they do.

Architecture of a Polarion Application: the view runs in an iframe inside the Polarion page, talks to the host through the SDK and to the server through fetch

From ZIP to running page

  1. An administrator uploads the ZIP in Global Administration → Applications. Polarion validates the structure, reads manifest.json, computes a SHA-2 hash and shows the identity of the application for confirmation.

  2. Polarion unpacks the files and serves them from

    https://<polarion-host>/polarion/apps/<identifier>/
    

    Each view also gets a stable entry URL that resolves to the document configured for it:

    https://<polarion-host>/polarion/apps/<identifier>/views/<viewId>
    
  3. An administrator places the view in the Polarion UI. Form extensions and navigation topics are referenced from configuration XML with an <applicationView id="p-introduction-how-it-works-<identifier>.<viewId>"/> element. Sidebars need no configuration: they appear in the Show Sidebar menu as soon as the application is uploaded.

  4. When a user opens that place, Polarion creates an iframe pointing at the view URL. Your index.html loads, your JavaScript runs, and the page is shown inside the Polarion layout.

Inside the iframe

Because the view is served from the same origin as Polarion, the browser applies no cross-origin restrictions between your page and the host page. The iframe is a structural boundary, not a security boundary: a same-origin frame could reach into the parent document. Treat an application as code that runs with the user's privileges, install only applications you trust, and communicate with Polarion through the defined protocol rather than by reaching into the parent window.

The host bridge and the SDK

The Polarion page contains a small host bridge that listens for postMessage calls from application iframes. The Polarion Application SDK (polarion-app-sdk) wraps that protocol:

The protocol itself (message types such as polarion-view-bridge) is an implementation detail. Always go through the SDK rather than posting messages yourself.

Warning: First version of the SDK

The SDK API of Polarion 2612 is a first version and is subject to change, including the functions above. Changes will be announced with the release that brings them, together with clear migration steps.

HTTP calls

Everything else is ordinary fetch():

Target URL Authentication
Polarion REST API context.restBaseUrl + /projects/… Header X-Polarion-REST-Token: <context.restToken>
Your own endpoints context.appEndpoint + /<urlPath> Required X-Polarion-REST-Token header; no session authentication
Your own static files relative URLs inside the view folder Polarion session

The token identifies the user who is logged in to Polarion. Every REST call and every server script runs with that user's permissions. See Security model.

Server scripts

A server script is a JavaScript file in the server-scripts/ folder of the package, mapped to an HTTP method and path in the manifest. Polarion executes it with GraalVM on the server when the endpoint is called. The script receives the request parameters through an arguments object and gets the Polarion Java API through context.scriptContext(). Whatever object the script evaluates to is returned to the caller as JSON, wrapped in a small envelope.

Server scripts are optional. Many applications only need the REST API. Reach for a script when you need to aggregate across many objects in one round trip, walk link structures, or use an API that REST does not expose. See Your own REST endpoints.

Life cycle of a view

  1. Polarion creates the iframe and loads index.html.
  2. Your code calls fetchContext() and renders.
  3. Optionally your code subscribes to events and keeps rendering as they arrive.
  4. When the user navigates away, the iframe is destroyed. Call destroy() from your framework's unmount hook so pending requests and subscriptions are cleaned up; this matters mostly during local development with hot reloading.

Views are stateless from Polarion's point of view. If you need to persist data, use work item fields, custom fields, comments or attachments through the REST API, or an external service of your own.

Info: Session Expiry and Reload Behavior

When a user's session expires and they log back in, the Polarion Application frame reloads automatically. (All unsaved changes within the application view are lost.)

Introduction

Roadmap and release notes

Polarion Applications are designed as the long-term extensibility framework of Polarion. This page describes what the 2612 preview contains, the direction for the next releases, and the differences to earlier internal previews.

Shipped in Polarion 2612 (preview)

The feature is disabled by default and is switched on with the polarionapp.enabled configuration property. See Enable Applications in Polarion.

Direction

The framework is built to grow along two axes. Dates and scope are indicative and subject to change; the manifest format is versioned (manifestVersion) so that applications can declare what they need.

More places in the UI

View type Status Purpose
Form extension 2612 Panel in the Work Item form
Sidebar 2612 Sidebar in the Work Items table and in Documents
Navigation topic 2612 Full page in the project navigation
Widget planned Application-provided widgets for LiveReport pages, dashboards and Documents
Administration view planned Pages in Project and Global Administration for configuring the application itself

See Upcoming: widgets and administration for how to prepare.

More content an application can deliver

Content Status Purpose
Views and endpoints 2612 UI and server-side capability
Scripts planned Workflow functions, conditions and scheduled scripts shipped and versioned with the application
Templates planned Project templates, document templates and configuration delivered by the application
Further resource types planned Enumerations, custom fields and other configuration as part of a package

The goal is that everything an extension needs travels in one package, is installed in one step, and is updated as a unit.

SDK

The SDK will gain events beyond selection-changed and calls from the view into the host (refreshing a form, navigating, notifications). The current API (fetchContext, events.subscribe, destroy) is a first version and is subject to change; each change will come with clear migration steps.

Changes compared with earlier previews

If you have seen pre-release material (for example workshop starters that used a polarion.js helper file), note the following differences. Applications built against the earlier protocol do not work on 2612 without changes.

Earlier preview Polarion 2612
Manifest sections workItemForms and viewlets.navigation views.formExtensions, views.sidebars, views.navigationTopics
Manifest section endpoints serverScripts.endpoints
No publisher field publisherName (shown in the upload dialog and in Properties)
Copy of a polarion.js helper in every app npm package polarion-app-sdk
Bridge messages polarion-viewlet-bridge* (internal names) polarion-view-bridge* (internal to the SDK)
Context { data: { restBase, objectId } } Flat PolarionContext with projectId, workItemId, restBaseUrl, appEndpoint, restToken, …
Form layout element <extension applicationId="…" viewletId="…"/> <applicationView id="p-introduction-roadmap-<identifier>.<viewId>"/>
REST token obtained from window.getRestApiToken() context.restToken from fetchContext()
ZIP with manifest.json at the root (some drafts) ZIP with one top-level folder named after the identifier

Known limitations in 2612

See Limitations and known issues for the complete list. The most important ones:

Getting started

Prerequisites

Before building an application, make sure the following is available on your computer and on the Polarion server.

On your computer

Requirement Notes
Node.js 20.19 or newer (22 LTS recommended) Vite 7 requires Node 20.19+. Check with node --version.
npm Ships with Node.js. The SDK is installed with npm from a URL on your Polarion server.
A code editor Visual Studio Code or any editor with TypeScript support.
A way to create ZIP files The examples include a small Node script; a plain zip command or the operating system's Compress function works as well, as long as the folder layout is correct.
Network access to the Polarion server To download the SDK package and to upload the application.

You do not need Java, Maven, the Polarion Java SDK or server file-system access.

On the Polarion server

Requirement Notes
Polarion 2612 Earlier releases do not contain the Applications feature. The server version is shown on the login page.
Applications enabled The global configuration property polarionapp.enabled=true must be set in Global Administration. See Enable Applications in Polarion.
REST API enabled with token authentication The properties com.siemens.polarion.rest.enabled=true and com.siemens.polarion.rest.security.restApiToken.enabled=true in polarion.properties. Required for views that call the REST API or server scripts.
Administrator access Uploading an application requires Global Administration. Placing views in forms and navigation requires project administration.

A project to work in

Pick or create a project you can experiment in. The walkthrough uses a project with the identifier test and a work item type Task in its examples; the screenshots in this guide come from the Drive Pilot demo project (work item type Work Package). Adjust the names to your project. You need at least one work item of the type whose form you will extend.

Optional: the SDK source and a reference application

The SDK is open for inspection. Its TypeScript source and README are available in the repository polarion-app-sdk-preview, and a complete reference application (tsapp-1) demonstrates all three view types together with server scripts. The examples in this guide are smaller and build on the same conventions.

Getting started

Enable Applications in Polarion

Polarion Applications are part of the Early Access Program in Polarion 2612 and are switched off by default. Two settings are involved: one enables the feature itself, the other lets views authenticate against the REST API and application endpoints.

1. Enable the Applications feature

The global configuration property polarionapp.enabled controls whether the Applications topic exists in Global Administration and whether uploaded applications are served. It is set in the Polarion UI only; there is no corresponding entry in polarion.properties.

  1. Log in as a user with global administration rights.
  2. Open Global Administration (avatar menu → Global Administration, or the wrench icon).
  3. Open Configuration Properties at the bottom of the administration navigation.
  4. Set the property

    polarionapp.enabled=true
    
  5. Save and reload the browser page.

A new Applications entry appears in the Global Administration navigation. It is only available at the repository (global) level, not in project administration.

The Applications topic in Global Administration after enabling the feature

2. Enable REST API token authentication

Views receive a short-lived REST token in their context and must send it in the X-Polarion-REST-Token header for REST API and application endpoint calls. Application endpoints do not accept browser-session authentication. This requires the REST API and its token mechanism to be enabled in polarion.properties on the server:

com.siemens.polarion.rest.enabled=true
com.siemens.polarion.rest.security.restApiToken.enabled=true

These two properties are read at start-up, so Polarion must be restarted after changing them. Without them, Polarion shows the warning X-Rest-Token generation is not allowed on the server! when a view opens, context.restToken is empty and REST API and application endpoint calls from views fail.

Warning shown when token authentication is not enabled

The same properties are also needed if you plan to automate uploads through the REST API with a personal access token.

3. Verify

If something is missing, see Troubleshooting.

Getting started

Your first application

In this walkthrough you build Hello Polarion: a form extension that shows a greeting and nothing else. No SDK, no state, no calls to Polarion; the point is the development loop, and you go through every step of it once: create the project, write the view, package the ZIP, upload it, and place it in a work item form. Reading the context and calling Polarion come next, in the Application context example.

The finished Hello Polarion panel inside a work item of the Drive Pilot demo project

The complete source is in examples/hello-polarion, where you can also download the finished application package and the source project. You can follow along from scratch or open the example side by side.

Tip: Before you start

Make sure the prerequisites are met and that an administrator has enabled Applications on your Polarion server. You need the host name of that server; the walkthrough uses polarion.example.com as a placeholder.

1. Create the project

  1. Scaffold a Vite project with the React + TypeScript template and install its dependencies:

    npm create vite@latest hello-polarion -- --template react-ts
    cd hello-polarion
    npm install
    
  2. Make Vite emit relative asset URLs. Polarion serves the view from a sub-path such as /polarion/apps/com.example.hello/hello/, so absolute /assets/… URLs would not resolve. Replace vite.config.ts with:

    vite.config.ts
    import { defineConfig } from "vite";
    import react from "@vitejs/plugin-react";
    
    // https://vite.dev/config/
    export default defineConfig({
      plugins: [react()],
      // Polarion serves the view from a sub-path such as
      // /polarion/apps/<identifier>/<rootDirectory>/, so all asset URLs must be relative.
      base: "./",
    });
    
  3. Remove the template files you do not need (src/App.css, src/index.css, src/assets/, public/vite.svg) and make sure index.html is a plain host page:

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Hello Polarion</title>
      </head>
      <body>
        <div id="root"></div>
        <script type="module" src="/src/main.tsx"></script>
      </body>
    </html>
    

2. Describe the application: manifest.json

Create manifest.json in the project root. It tells Polarion what the application is called and which views it contains.

manifest.json
{
  "manifestVersion": "1.0",
  "identifier": "com.example.hello",
  "title": "Hello Polarion",
  "description": "The smallest possible Polarion Application: one form extension that says hello.",
  "publisherName": "Example Publisher",
  "applicationVersion": "0.2.0",
  "views": {
    "formExtensions": [
      {
        "identifier": "hello",
        "title": "Hello Polarion",
        "rootDirectory": "hello",
        "document": "index.html"
      }
    ]
  }
}

What the fields mean:

Field Meaning
identifier Unique name of the application on the server. Reverse-DNS style (com.example.hello) is recommended. It becomes part of every URL and configuration id, so keep it short and stable.
manifestVersion, title, description, publisherName, applicationVersion Shown to the administrator during upload and in Properties.
views.formExtensions[0].identifier The view id. Together with the application identifier it forms the id used in configuration: com.example.hello.hello.
rootDirectory, document Where the view's files live inside the package and which file is the entry page.

The full schema is in the manifest.json reference.

3. Write the view

  1. Replace src/main.tsx:

    src/main.tsx
    import { StrictMode } from "react";
    import { createRoot } from "react-dom/client";
    import App from "./App";
    import "./styles.css";
    
    createRoot(document.getElementById("root")!).render(
      <StrictMode>
        <App />
      </StrictMode>,
    );
    
  2. Replace src/App.tsx. The view is an ordinary React component; nothing in it is specific to Polarion:

    src/App.tsx
    export default function App() {
      return (
        <main>
          <h1>Hello, Polarion</h1>
          <p>This panel is a Polarion Application.</p>
        </main>
      );
    }
    

    What makes it a Polarion Application is the packaging: the manifest, the ZIP layout and the place in the form layout, in the next steps. The page does not need the SDK to be shown; the SDK comes in when the view wants to know where it is or call Polarion.

  3. Add src/styles.css with a little styling:

    src/styles.css
    body {
      margin: 0;
      padding: 12px;
      font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
      font-size: 14px;
      color: #1f2933;
    }
    
    h1 {
      font-size: 1.4rem;
      margin: 0 0 8px;
    }
    
  4. Build once to check that everything compiles:

    npm run build
    

    Vite writes dist/index.html and dist/assets/…. Open dist/index.html and confirm that the script and stylesheet paths start with ./assets/.

4. Package the ZIP

Polarion expects a ZIP with one top-level folder named after the identifier. Inside it: manifest.json, one folder per view (named like rootDirectory), and optionally server-scripts/.

A ZIP with manifest.json directly at its root is rejected with Application's zip structure is incorrect. For the file types a package may contain and its size limits, see Allowed file types and Validation and limits.

Node script (any OS)

Add scripts/package.mjs and the dev dependency adm-zip. The script copies the build into the right layout and writes the ZIP:

npm install --save-dev adm-zip
scripts/package.mjs
// Builds the upload-ready ZIP for Polarion.
//
// Layout inside the ZIP: one top-level folder named after the application
// identifier, with manifest.json, view content under each view's
// rootDirectory (which multiple views may share), and optional server-scripts/.
// Polarion rejects a ZIP that has manifest.json directly at its root
// ("Application's zip structure is incorrect").
//
//   <identifier>/
//     manifest.json
//     <rootDirectory of each view>/   (index.html + assets)
//     server-scripts/                 (if present)
//
// Single-view projects build into dist/. Multi-view projects build one Vite
// mode per view into dist/<rootDirectory>/ (see "Set up the project" in the
// guide); this script copies whichever exists.
//
// Run with `npm run package` (which builds first).
import { cpSync, existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import AdmZip from "adm-zip";

const projectRootPath = fileURLToPath(new URL("..", import.meta.url));
const distributionPath = join(projectRootPath, "dist");

function stageViews(appStagePath, manifest) {
  const views = Object.values(manifest.views ?? {}).flat();
  if (views.length === 0) {
    throw new Error("manifest.json declares no views.");
  }

  for (const view of views) {
    const viewDist = join(distributionPath, view.rootDirectory);
    const source = existsSync(viewDist) ? viewDist : distributionPath;
    const documentPath = join(source, view.document);

    if (!existsSync(documentPath)) {
      throw new Error(`Build output for view "${view.identifier}" not found: ${documentPath}`);
    }
    cpSync(source, join(appStagePath, view.rootDirectory), { recursive: true });
  }
}

function stageServerScripts(appStagePath) {
  const serverScripts = join(projectRootPath, "server-scripts");
  if (existsSync(serverScripts)) {
    cpSync(serverScripts, join(appStagePath, "server-scripts"), { recursive: true });
  }
}

function writePackageZip(stageRoot, zipPath) {
  const zip = new AdmZip();
  zip.addLocalFolder(stageRoot);
  zip.writeZip(zipPath);
}

function packageApplication() {
  const manifest = JSON.parse(readFileSync(join(projectRootPath, "manifest.json"), "utf8"));
  const stageRootPath = join(projectRootPath, "package");
  const zipPath = join(projectRootPath, `${manifest.identifier}.zip`);

  rmSync(stageRootPath, { recursive: true, force: true });
  try {
    const appStagePath = join(stageRootPath, manifest.identifier);
    mkdirSync(appStagePath, { recursive: true });
    cpSync(join(projectRootPath, "manifest.json"), join(appStagePath, "manifest.json"));
    stageViews(appStagePath, manifest);
    stageServerScripts(appStagePath);
    writePackageZip(stageRootPath, zipPath);
  } finally {
    rmSync(stageRootPath, { recursive: true, force: true });
  }

  console.log(`Packaged ${manifest.identifier} ${manifest.applicationVersion} -> ${zipPath}`);
}

packageApplication();

Then add two npm scripts to package.json and run the packaging:

package.json (scripts)
"scripts": {
  "dev": "vite",
  "build": "tsc -b && vite build",
  "package": "npm run build && node scripts/package.mjs"
}
npm run package
# Packaged com.example.hello 0.2.0 -> …/com.example.hello.zip

Shell (macOS / Linux)

npm run build
rm -rf package && mkdir -p package/com.example.hello
cp manifest.json package/com.example.hello/
cp -R dist package/com.example.hello/hello
(cd package && zip -r ../com.example.hello.zip com.example.hello)

PowerShell (Windows)

npm run build
Remove-Item -Recurse -Force package -ErrorAction Ignore
New-Item -ItemType Directory package\com.example.hello | Out-Null
Copy-Item manifest.json package\com.example.hello\
Copy-Item -Recurse dist package\com.example.hello\hello
Compress-Archive -Path package\com.example.hello -DestinationPath com.example.hello.zip -Force

5. Upload the application

  1. In Polarion open Global Administration → Applications and click Upload.

  2. Choose com.example.hello.zip and click Next.

    Upload Application dialog, step 1: choose the ZIP file

  3. Polarion validates the package and shows what it is about to install: identifier, version, title, publisher and the SHA-2 hash of the file. Compare the hash with the one you computed if your organization requires it, then click Finish.

    Upload Application dialog, step 2: review identity and hash, then Finish

  4. A green bar confirms Application 'com.example.hello' was uploaded and the tile appears in the list. Hover the tile to see the description; select it and click Properties to see the manifest data.

    The Applications page after a successful upload

The application is now installed but not yet visible anywhere. Views have to be placed.

6. Place the view in a work item form

Form extensions are positioned by the administrator in the form layout of a work item type, per project.

  1. Open your project and go to Administration → Work Items → Form Configuration.

  2. In the Form Layouts table at the bottom of the page, click Edit next to the work item type you want to extend (for example Task). If the type has no layout yet, click Create New Form Layout first.

  3. In the XML editor, insert an applicationView element where the panel should appear. The id is <identifier>.<viewId>:

    Form layout (excerpt)
    <formLayout …>
      <horizontal>
        …
      </horizontal>
      <applicationView id="com.example.hello.hello" label="Hello Polarion" height="320px"/>
      <field id="description"/>
      <field id="comments"/>
      …
    </formLayout>
    

    label sets the heading of the panel (default: Polarion Application). height sets the height of the iframe.

    Form layout editor with the applicationView element inserted

  4. Click Save. The message Configuration has been saved appears.

  5. Open any work item of that type. Reload the page if it was already open. The Hello Polarion panel shows the greeting.

    Hello Polarion rendered in the work item form

Note: If a Warning dialog appears

A dialog saying X-Rest-Token generation is not allowed on the server means the server lacks REST token authentication. The panel still renders, but REST calls will fail; see Enable Applications in Polarion.

What you have learned

Continue with Iterate: change, rebuild, re-upload to learn the development loop. To see what a view learns about its surroundings, install the Application context example; the Work item card then shows the REST API in action.

Getting started

Iterate: change, rebuild, re-upload

Once the first version is installed, every further change follows the same short loop.

The loop

  1. Edit the source.
  2. npm run package (build + ZIP).
  3. Global Administration → Applications → Upload the new ZIP.
  4. Reload the Polarion page that shows the view (hard reload: Ctrl+Shift+R or Cmd+Shift+R).

Configuration XML does not have to be touched again unless you rename the application identifier or add a new view.

Updating an installed application

Uploading a ZIP whose identifier matches an installed application updates it in place. The confirmation step of the upload dialog changes accordingly: it reads You are going to UPDATE the following application and shows two columns, New Version and Current Version, with the manifest data of both.

Upload dialog when the identifier already exists: New Version next to Current Version

Bump applicationVersion with every upload. The update dialog shows it next to the installed version, administrators see it in Properties, and it is the only reliable way to tell two builds apart.

Browser caching: Vite gives every build output a content hash in its file name, so a new build never collides with cached assets. The entry index.html itself is small and is reloaded with the page.

Checking what is installed

Select a tile on the Applications page and click Properties. The dialog shows the identifier, version, title, publisher, manifest version and description taken from the installed manifest.

Application Properties dialog

The static files are also reachable directly, which is useful for a quick check that a build made it to the server:

https://<polarion-host>/polarion/apps/<identifier>/<rootDirectory>/index.html

Opening a view this way shows your page without the Polarion host around it. fetchContext() cannot succeed there; a well-written view reports that instead of hanging (see the error state in Your first application).

Removing an application

Select the tile and click Delete. Polarion removes the application and its files immediately and confirms with Application <identifier> was deleted; treat the button as final. Configuration XML that still references a view of the deleted application is not changed; the corresponding panel simply disappears from forms and the entry vanishes from the Show Sidebar menu. Remove the applicationView elements by hand to keep the configuration clean.

Several developers, one server

Application identifiers are global on a server. Two people uploading com.example.hello overwrite each other. During development, give every developer or feature branch its own identifier (for example com.example.hello.jdoe) and switch to the final identifier when the application is ready. Remember that the identifier is part of the configuration id, so the applicationView elements must follow.

Local development without uploading

Rebuilding and uploading for every CSS tweak is slow. For UI work, run npm run dev and open the Vite dev server in a browser; fetchContext() fails there, so give your code a mock context in development mode. The pattern is described in Develop locally.

Getting started

Build an application with AI

AI coding assistants can write a Polarion Application for you, but they do not know Polarion Applications from their training: the framework is new in 2612. The AI kit gives them what they need. It contains this whole guide, the seven example applications and a set of instructions for the assistant, all in one folder that works offline.

Three steps

  1. Unzip the kit and open the folder in your AI coding assistant, for example Claude Code, GitHub Copilot in VS Code, or Cursor. The assistant reads AGENTS.md (also provided as CLAUDE.md and .github/copilot-instructions.md), which explains how Polarion Applications work and which rules they follow.
  2. Paste the prompt below and replace the part in angle brackets with what you want: what the application shows or does, where it appears, and what it reads or changes.
  3. Upload the result. The assistant builds a ZIP file. Upload it in Global Administration → Applications and place it as the assistant describes, first on a test server. See Package and upload.
Prompt
Read AGENTS.md in this folder and follow it. Then build a Polarion Application that <describe what it should show or do, where it should appear (on the work item form, next to the Work Items table, or as a page in the project navigation), and what it reads or changes>. Start from the closest example, build and package it, and tell me how to upload and place it.

The assistant needs Node.js 20.19 or newer (22.12 or newer on Node 22) to build the application; see Prerequisites. Your Polarion server needs Applications enabled and REST token authentication on; see Enable Applications in Polarion.

Example requests

Each of these replaces the part in angle brackets:

The more precise the request, the better the result: name the work item types, fields and link roles your project uses.

What is in the kit

File or folder For Content
START-HERE.html you These steps and the prompt, to open in a browser
Guide.html you This guide as one page, readable offline
AGENTS.md the assistant How to work, the view types, and the rules that a Polarion Application must follow: package layout, allowed file types, SDK, context, REST API and endpoints
guide/ the assistant Every page of this guide as plain Markdown, and guide/ALL.md with all pages in one file
examples/ both The sources of the seven examples and the SDK package

The kit is generated from this guide and its examples whenever they change, so the download always matches the pages you are reading.

What to expect

Views

Views: where your application lives

A view is one web page of your application placed at one kind of location in the Polarion UI. (If you have not read it yet, Application context explains the context object the view pages refer to.) The location is the first decision of every application: it determines what the user is looking at when your page opens, what the framework tells you about the surroundings, and how the administrator switches it on. Polarion 2612 offers three view types; an application may contain any number of each. Sidebars inside Documents and the create form of a new work item are described as the SDK documents them; the screenshots in this guide were taken in the Work Items table and in saved work items.

The three view types

Form extension

A form extension panel below the field sections of a work item

A collapsible panel inside the Work Item form, placed among the fields by the administrator. The view knows which work item is open. Use it for everything that is about this work item: data from other systems, link visualizations, guided editing, checklists.

Form extension in detail →

Sidebar

The Show Sidebar menu listing an application sidebar next to the built-in ones

A panel in the sidebar area next to the Work Items table and inside Documents, chosen by the user from the Show Sidebar menu. The view receives the current selection and every change to it. Use it for inspectors, bulk actions and checks on whatever the user selects.

Sidebar in detail →

Navigation topic

A navigation topic rendered as a full page

A full page with its own entry in the project navigation. The view gets the whole content area and knows the project. Use it for dashboards, reports, planning boards and editors.

Navigation topic in detail →

Comparison

Form extension Sidebar Navigation topic
Manifest list views.formExtensions views.sidebars views.navigationTopics
Switched on by applicationView in the form layout nothing (listed in Show Sidebar) applicationView in the Topics configuration
Context knows project, work item project, selection, document project
Events – selection-changed –
Space panel of configurable height narrow column, full height whole content area
Lifetime per work item while the table or document is open while the page is open

Choosing a view type

You want to… Use
Show or edit something about the work item the user is looking at Form extension
React to what the user selects in a table or document Sidebar
Offer a tool or report at project level Navigation topic
Do several of the above Several views in one application, sharing code

A common combination is a sidebar for selection-driven actions plus a navigation topic for the overview, or a form extension plus endpoints that compute something per work item on the server.

What all views have in common

Coming next

The framework is designed to accept more view types. Widgets for pages and reports and administration views are planned; see Upcoming: widgets and administration for what to expect and how to structure an application so that adding them later is cheap.

Views

Form extension

A form extension is a panel inside the Work Item form. Polarion renders it as a collapsible section with a heading, like Description or Comments, and loads your view in an iframe inside it.

Form extension panel in a Work Package of the Drive Pilot demo project

Declare the view

manifest.json (excerpt)
"views": {
  "formExtensions": [
    {
      "identifier": "card",
      "title": "Work item card",
      "rootDirectory": "card",
      "document": "index.html"
    }
  ]
}

title appears to be informational in 2612; the panel heading comes from the label attribute in the form layout.

Place it in a form layout

Form layouts are configured per project, per work item type, and per Polarion View (hat; most projects only use Default).

  1. Open the project and go to Administration → Work Items → Form Configuration.
  2. Scroll to Form Layouts. Click Edit for the work item type, or Create New Form Layout if the type has none yet (then choose the View and type).
  3. Insert the element where the panel should appear and click Save.
Form layout
<?xml version="1.0" encoding="UTF-8"?>
<formLayout xmlns="http://polarion.com/schema/WorkItems/FormLayout" …>
  <horizontal>
    <vertical>
      <section>…</section>
    </vertical>
  </horizontal>
  <field id="description"/>
  <applicationView id="com.example.workitemcard.card" label="Work item card" height="640px"/>
  <field id="comments"/>
  <field id="linkedWorkItems"/>
</formLayout>

The form layout editor

Attributes

Attribute Required Meaning
id yes <application identifier>.<view identifier>
label no Heading of the panel. Default: Polarion Application.
height no CSS height of the iframe, for example 320px. Default: 600px. The iframe does not grow with its content; size it for your view or make the view scroll internally.

applicationView is a top-level element of the layout, a sibling of <field>, <horizontal> and <extension>. It cannot be placed inside <section> or <panel>.

The same view can be referenced in several layouts (several types, several projects). Each occurrence gets its own iframe.

Where the panel shows up

The form layout applies to every place that renders the Work Item form: the editor below the Work Items table, the full-page work item view and, as far as the layout is shared, the work item editor opened from a Document. Your view is loaded in each of them.

Context in a form extension

{
  "applicationId": "com.example.workitemcard",
  "viewId": "card",
  "projectId": "test",
  "workItemId": "TEST-514",
  "selectedWorkItemIds": ["test/TEST-514"],
  "appEndpoint": "…/polarion/apps/com.example.workitemcard/rest",
  "restBaseUrl": "…/polarion/rest/v1",
  "restToken": "…"
}

When the form is opened from a Document, spaceId and documentId are also set. In the multi-item edit form below the Work Items table, opened by ticking several rows, a form extension gets all ticked items in selectedWorkItemIds (for example ["drivepilot/DP-477", "drivepilot/DP-461", "drivepilot/DP-393"]), while workItemId is the current item (DP-477). Observed on Polarion 2612.

Creating a new work item

In the create form (a work item that is not saved yet) there is no workItemId. Handle the missing field by rendering a short hint; most panels have nothing useful to show before the item exists.

Design notes

Removing

Delete the applicationView element from the layout and save. Deleting the application without editing the layout also removes the panel, but leaves a dangling reference in the configuration.

Views

Sidebar

A sidebar is a view shown in the sidebar area of the Work Items table and of Documents, alongside Polarion's own sidebars such as Approvals and Planning. Sidebars are the right place for anything that reacts to the user's selection.

The Show Sidebar menu with an application sidebar entry

Declare the view

manifest.json (excerpt)
"views": {
  "sidebars": [
    {
      "identifier": "selection",
      "title": "Selection inspector",
      "rootDirectory": "selection",
      "document": "index.html",
      "menuIcon": "icon16.png",
      "icon": "icon32.png"
    }
  ]
}
Field Meaning
title Label in the Show Sidebar menu and in the sidebar header.
menuIcon 16 × 16 px image shown in the menu. Path relative to rootDirectory.
icon 32 × 32 px image shown in the sidebar header.

Put the icons in public/ of the Vite project so that they end up at the root of the view folder. The examples use PNG with transparency (verified); the menu draws the 16 px icon on a light background and the sidebar header draws the 32 px icon on dark navy, so avoid icons that rely on one background color.

No configuration needed

Sidebars are not placed with XML. As soon as the application is uploaded, every sidebar it declares is offered in the Show Sidebar menu of every project. Users open it with one click; Polarion keeps it open while they navigate the table.

Note: Planned: sidebar configuration

This applies to Polarion 2612. Configuration for sidebars is planned for Polarion 2706.

The open sidebar is part of the URL, so links and bookmarks can include it:

https://<host>/polarion/#/project/test/workitems?sidebar=polarion-application.com.example.selectionsidebar.selection

An application sidebar opened next to the Work Items table

Context and events

On open, fetchContext() returns projectId; inside a Document also spaceId and documentId. The selection is not in the context: selectedWorkItemIds is empty in sidebars on Polarion 2612. Subscribe to selection-changed to learn what is selected; see React to selection changes.

Design for the column

Typical uses

Removing

Delete the application, or remove the view from the manifest and re-upload. The entry disappears from the menu; users who had it open see an empty sidebar until they choose another one.

Views

Navigation topic

A navigation topic is a full page of your own in a project. It gets an entry in the navigation panel on the left, with your icon and title, and the whole content area when opened.

A navigation topic page: the Project dashboard example

Declare the view

manifest.json (excerpt)
"views": {
  "navigationTopics": [
    {
      "identifier": "dashboard",
      "title": "Project dashboard",
      "icon": "icon30.png",
      "rootDirectory": "dashboard",
      "document": "index.html"
    }
  ]
}
Field Meaning
title Label in the navigation panel and in the page header.
icon 30 × 30 px image shown in the navigation panel, the size of Polarion's own topic icons (the image is rendered at its natural size). Path relative to rootDirectory. The panel background is dark navy; use a PNG with transparency and light or saturated colors.

Add it to the navigation

Topics are configured per project and per Polarion View (hat).

  1. Open the project and go to Administration → Portal → Topics.
  2. Click the View you want to change (usually Default). The Topics Configuration XML opens.
  3. Add an applicationView element among the <topic> elements. Its position determines the position in the navigation panel.
  4. Click Save and reload the project.
Topics configuration
<?xml version="1.0" encoding="UTF-8"?>
<topics xmlns="http://polarion.com/schema/Portal/Topics" …>
  <topic id="workitems"/>
  <topic id="wiki"/>
  <topic id="plans"/>
  <topic id="testruns"/>
  <topic id="reports"/>
  <applicationView id="com.example.dashboard.dashboard"/>
  <topic id="global_shortcuts"/>
  <topic id="project_shortcuts"/>
  <topic id="user_shortcuts"/>
</topics>

The Topics configuration editor with an applicationView element

The id is <application identifier>.<view identifier>. There are no other attributes; the title and icon come from the manifest. The topic appears at the configured position in the navigation panel, and its page has a stable URL built from the same id:

https://<host>/polarion/#/project/<projectId>/<application identifier>.<view identifier>

The navigation panel with the Project dashboard topic between Monitor and the shortcuts

The same configuration also exists at repository level (Global Administration → Portal → Topics) as the default for projects without their own configuration.

Context in a navigation topic

{
  "applicationId": "com.example.dashboard",
  "viewId": "dashboard",
  "projectId": "test",
  "selectedWorkItemIds": [],
  "appEndpoint": "…/polarion/apps/com.example.dashboard/rest",
  "restBaseUrl": "…/polarion/rest/v1",
  "restToken": "…"
}

Only the project is known. Everything else the page needs comes from the REST API or from server scripts. There are no events.

Linking into Polarion

A dashboard usually links to work items, documents or plans. Build the URLs from the context and open them in the top window so that the whole Polarion UI navigates:

<a href={`${window.location.origin}/polarion/#/project/${projectId}/workitem?id=${id}`} target="_top">

Without target="_top" the link would load inside your iframe.

Design notes

Removing

Delete the applicationView element from the Topics configuration and save. The navigation entry disappears immediately.

Views

Upcoming: widgets and administration

The three view types of Polarion 2612 cover the work item form, the table and document sidebars, and the project navigation. Two further view types are planned. This page describes their intended role so that you can design applications with them in mind. Details are subject to change until they ship.

Widget

A widget view will let an application contribute widgets to the places where Polarion renders widgets today: LiveReport pages, dashboards and rich pages, and Document content. Each widget is a small web page with parameters that the page author sets when placing it. Expected characteristics:

Typical uses: KPI tiles fed by your own endpoints, charts over data from external systems, interactive tables with actions.

Administration view

An administration view will give an application pages in Project Administration and Global Administration. This is where an application configures itself: connection settings for an external system, mapping tables, feature switches, per-project rules. Expected characteristics:

Typical uses: an Integration settings page next to the built-in administration topics; a rule editor for a validation application; a place to enter the webhook of a chat tool.

Designing for what is coming

Also on the roadmap

Beyond views, applications will carry more kinds of content: scripts (workflow functions, scheduled scripts), templates and other configuration, so that an extension ships as one versioned package. See Roadmap and release notes.

Polarion REST API

Calling the REST API from a view

Polarion's REST API is the main way for a view to read and change data. The context gives you everything you need to call it: restBaseUrl and restToken.

Note: REST API documentation

This page covers what is specific to calling the API from an application view. The API itself is documented in the Polarion REST API User Guide on the Siemens Xcelerator Developer Portal, and your server publishes its OpenAPI definition at https://<polarion-host>/polarion/rest/v1/definition.

A small helper

The examples that call the REST API use the same small helper, restFetch. Calls to your own endpoints go through its counterpart endpointFetch (see Call endpoints from a view). restFetch adds the token, sets the JSON headers, throws on HTTP errors and returns the parsed body:

src/polarion.ts
import type { PolarionContext } from 'polarion-app-sdk';

/**
 * Calls the Polarion REST API (JSON:API) on behalf of the logged-in user.
 *
 * `context.restBaseUrl` is the absolute base URL of the REST API, for example
 * `https://host/polarion/rest/v1` (no trailing slash). `context.restToken` is a
 * short-lived token that Polarion hands to the application view; it must be
 * sent in the `X-Polarion-REST-Token` header.
 */
export async function restFetch<T>(context: PolarionContext, path: string, init: RequestInit = {}): Promise<T> {
  const headers = new Headers(init.headers);
  headers.set('X-Polarion-REST-Token', context.restToken ?? '');
  headers.set('Accept', 'application/json');
  if (init.body !== undefined && !headers.has('Content-Type')) {
    headers.set('Content-Type', 'application/json');
  }

  const response = await fetch(`${context.restBaseUrl}${path}`, { ...init, headers });
  if (!response.ok) {
    throw new Error(`REST ${response.status}: ${await response.text()}`);
  }
  if (response.status === 204) {
    return null as T;
  }
  return (await response.json()) as T;
}
// WorkItemResponse and the other types live in src/types.ts of the examples.
const item = await restFetch<WorkItemResponse>(
  context,
  `/projects/${context.projectId}/workitems/${context.workItemId}?fields[workitems]=id,title,status`,
);

Authentication

Send the header on every request:

X-Polarion-REST-Token: <context.restToken>

The token represents the logged-in user. Calls fail with 401 if the token is missing, empty (token authentication not enabled on the server) or expired, and with 403 if the user lacks permission for the operation. On 401 after a long idle period, call fetchContext() again and retry once.

Do not send cookies or basic authentication; the token is sufficient and the recommended mechanism.

Reading a single resource

GET {restBaseUrl}/projects/test/workitems/TEST-514?fields[workitems]=id,title,status,type,description
{
  "data": {
    "type": "workitems",
    "id": "test/TEST-514",
    "attributes": {
      "id": "TEST-514",
      "title": "Brake pedal sensor",
      "status": "open",
      "type": "task",
      "description": { "type": "text/html", "value": "<p>…</p>" }
    },
    "links": { "self": "…" }
  }
}

Always ask for the fields you need with fields[<type>]=…. Without it the API returns a default set that omits most attributes; with @all it returns everything, which is slow for large items. Note that a sparse field set also filters relationships: to receive relationships.workItem on a link resource, workItem must be in fields[linkedworkitems].

Relationships are separate resources. To get the linked work items of an item together with their titles in one request:

GET {restBaseUrl}/projects/test/workitems/TEST-514/linkedworkitems
    ?fields[linkedworkitems]=role,suspect,workItem
    &include=workItem
    &fields[workitems]=id,title,status,type

The response has data (the link resources with a relationships.workItem.data.id) and included (the work items). Join them by id, as in the Work item card example.

Lists and queries

GET {restBaseUrl}/projects/test/workitems
    ?query=status:open AND type:task
    &sort=-created
    &fields[workitems]=id,title,status
    &page[size]=100&page[number]=1

A selection of ids becomes one query: id:(TEST-514 TEST-513 TEST-511).

Writing

Updates use PATCH with a JSON:API document that repeats type and id:

await restFetch(context, `/projects/test/workitems/TEST-514`, {
  method: 'PATCH',
  body: JSON.stringify({
    data: { type: 'workitems', id: 'test/TEST-514', attributes: { title: 'New title' } },
  }),
});

Polarion answers with a 2xx status and no body on success (the examples expect 204 No Content). Creating resources uses POST on the collection URL with data as an array; deleting uses DELETE. Writes go through the same workflow and permission checks as the UI, so a field that is read-only for the user's role is also read-only through the API.

After a write, the Polarion form or table around your view does not know about the change. Tell the user to reload, or navigate with a target="_top" link; the host bridge has no "refresh" call yet.

Encoding

Use URLSearchParams for query strings. It encodes the brackets in fields[workitems] and the spaces in Lucene queries correctly:

const params = new URLSearchParams({
  query: 'status:open AND type:task',
  'fields[workitems]': 'id,title,status',
  'page[size]': '100',
});
const url = `${context.restBaseUrl}/projects/${context.projectId}/workitems?${params}`;

Error handling

Status Meaning in a view What to do
400 Bad request shape or unknown field Fix the request; the body contains errors[].detail.
401 Missing or expired token Check that token authentication is enabled; refetch the context.
403 User may not do this Show a message; do not retry.
404 Wrong project/id, or no read permission Verify ids from the context.
409 Concurrent modification or workflow conflict Reload and let the user try again.

The error body is JSON:API as well:

{ "errors": [ { "status": "403", "title": "Forbidden", "detail": "…" } ] }

Performance notes

More in Performance and load.

Polarion REST API

Cookbook

The snippets below use the restFetch helper from Calling the REST API from a view and a context obtained from fetchContext(). Resource names and attribute ids follow the Polarion REST API v1 and were exercised against a 2612 server for reading work items (including created and the assignee relationship), Lucene queries, linked work items with include=workItem, PATCH of attributes and POST of comments. For the remaining recipes the OpenAPI definition of your server (https://<host>/polarion/rest/v1/definition) is the authority for field names and optional parameters.

Read one work item with chosen fields

const { data } = await restFetch<WorkItemResponse>(
  context,
  `/projects/${context.projectId}/workitems/${context.workItemId}` +
    `?fields[workitems]=id,title,type,status,priority,severity,description,created,updated`,
);
data.attributes.title;
data.attributes.description?.value;   // HTML

Read the assignee and author (relationships)

const { data, included } = await restFetch<WorkItemResponse>(
  context,
  `/projects/${p}/workitems/${id}?fields[workitems]=id,title,assignee,author&include=assignee,author&fields[users]=id,name,email`,
);
const assigneeIds = data.relationships?.assignee?.data?.map((u) => u.id) ?? [];   // ["admin"]
const users = new Map((included ?? []).map((u) => [u.id, u.attributes]));

Query work items

const params = new URLSearchParams({
  query: 'type:requirement AND status:open AND NOT HAS_VALUE:assignee',
  sort: '-updated',
  'fields[workitems]': 'id,title,status,type,updated',
  'page[size]': '100',
  'page[number]': '1',
});
const list = await restFetch<WorkItemListResponse>(context, `/projects/${p}/workitems?${params}`);
list.data;              // array of resources
list.meta?.totalCount;  // total across pages

The query syntax is the Lucene syntax of the Work Items table. A set of ids: id:(TEST-1 TEST-2 TEST-3).

Page through a large result

async function allWorkItems(context: PolarionContext, p: string, query: string) {
  const out: WorkItemResource[] = [];
  for (let page = 1; ; page++) {
    const params = new URLSearchParams({ query, 'fields[workitems]': 'id,title', 'page[size]': '100', 'page[number]': String(page) });
    const r = await restFetch<WorkItemListResponse>(context, `/projects/${p}/workitems?${params}`);
    out.push(...r.data);
    // Stop on the reported total, not on a short page: a server may cap page[size] below 100.
    const total = r.meta?.totalCount;
    if (r.data.length === 0 || (total !== undefined && out.length >= total)) return out;
  }
}

The loop ends when all items reported by meta.totalCount are collected, or when a page comes back empty. It does not rely on the requested page size, because the server can serve fewer items per page than requested.

For thousands of items, move the aggregation into an endpoint.

Update attributes

await restFetch(context, `/projects/${p}/workitems/${id}`, {
  method: 'PATCH',
  body: JSON.stringify({
    data: { type: 'workitems', id: `${p}/${id}`, attributes: { title: 'New title', priority: '90.0' } },
  }),
});

Enumeration fields take the option id (priority: '90.0', severity: 'must_have'), not the label.

Change the status

await restFetch(context, `/projects/${p}/workitems/${id}`, {
  method: 'PATCH',
  body: JSON.stringify({ data: { type: 'workitems', id: `${p}/${id}`, attributes: { status: 'inprogress' } } }),
});

The transition must be allowed by the workflow for the current status and the user's role; otherwise the API answers 400 or 403 with the reason in errors[].detail. Newer servers also expose explicit workflow actions (see …/workitems/{id}/actions in the definition).

Set the assignee

await restFetch(context, `/projects/${p}/workitems/${id}`, {
  method: 'PATCH',
  body: JSON.stringify({
    data: {
      type: 'workitems',
      id: `${p}/${id}`,
      relationships: { assignee: { data: [{ type: 'users', id: 'jdoe' }] } },
    },
  }),
});

Create a work item

const created = await restFetch<WorkItemListResponse>(context, `/projects/${p}/workitems`, {
  method: 'POST',
  body: JSON.stringify({
    data: [
      { type: 'workitems', attributes: { type: 'task', title: 'Follow-up', description: { type: 'text/html', value: '<p>Created by the app.</p>' } } },
    ],
  }),
});
created.data[0].id;   // "test/TEST-600"
await restFetch(context, `/projects/${p}/workitems/${id}/linkedworkitems`, {
  method: 'POST',
  body: JSON.stringify({
    data: [
      {
        type: 'linkedworkitems',
        attributes: { role: 'relates_to' },
        relationships: { workItem: { data: { type: 'workitems', id: `${p}/TEST-513` } } },
      },
    ],
  }),
});

Role ids come from the project's link role enumeration (relates_to, implements, verifies, …).

const r = await restFetch<LinkedWorkItemsResponse>(
  context,
  `/projects/${p}/workitems/${id}/linkedworkitems?fields[linkedworkitems]=role,suspect,workItem&include=workItem&fields[workitems]=id,title,status`,
);
const byId = new Map((r.included ?? []).map((wi) => [wi.id, wi]));
r.data.map((link) => ({ role: link.attributes.role, item: byId.get(link.relationships.workItem.data.id) }));

Add a comment

await restFetch(context, `/projects/${p}/workitems/${id}/comments`, {
  method: 'POST',
  body: JSON.stringify({
    data: [{ type: 'workitem_comments', attributes: { text: { type: 'text/html', value: '<p>Reviewed by the app.</p>' } } }],
  }),
});

Escape user input before putting it into HTML.

Read a Document and its work items

const doc = await restFetch<DocumentResponse>(
  context,
  `/projects/${p}/spaces/${context.spaceId}/documents/${context.documentId}?fields[documents]=title,type,status,updated`,
);
const parts = await restFetch<DocumentPartsResponse>(
  context,
  `/projects/${p}/spaces/${context.spaceId}/documents/${context.documentId}/parts?include=workItem&fields[workitems]=id,title,type`,
);

Test runs and records

const runs = await restFetch<TestRunListResponse>(context, `/projects/${p}/testruns?fields[testruns]=id,title,status,finishedOn&page[size]=50`);
const records = await restFetch<TestRecordListResponse>(
  context,
  `/projects/${p}/testruns/${runId}/testrecords?include=testCase&fields[testrecords]=result,executed&fields[workitems]=id,title`,
);

Enumerations (for select boxes)

const statuses = await restFetch<EnumerationResponse>(context, `/projects/${p}/enumerations/~/status/~`);
// options: statuses.data.attributes.options → [{ id, name, color, … }]

The exact path depends on the enumeration's context (work item type specific enumerations have their own path); check the definition.

Users

const me = await restFetch<UserResponse>(context, `/users/${userId}?fields[users]=id,name,email`);

Views do not know the current user's id directly; an endpoint can return it from the security service, or compare relationships.author of an item the user just created.

Error body

All errors share one shape:

{ "errors": [ { "status": "400", "title": "Bad Request", "detail": "…", "source": { "pointer": "$.data.attributes.status" } } ] }

Show detail to the user; it usually names the field or rule that failed.

Your own REST endpoints

Your own REST endpoints

An application is not limited to what the browser can do. It can declare its own REST endpoints: HTTP paths under the application's URL that Polarion routes to JavaScript files inside the package. The code runs on the Polarion server, as the user who made the call, with access to the Polarion Java API through the scripting bridge. This is how an application delivers functionality that goes beyond the standard REST API.

POST https://<host>/polarion/apps/com.example.releasechecklist/rest/validate
     X-Polarion-REST-Token: <context.restToken>
     {"objectId": "test/TEST-514", "objectIds": "[\"test/TEST-514\",\"test/TEST-513\"]"}

→    {"timestamp": "…", "success": true,
      "data": {"results": [...], "summary": {"items": 2, "withFindings": 1, ...}}}

The Release checklist sidebar, whose findings are computed by an endpoint of the application

What an endpoint gives you

Capability Why it matters
One request, any amount of work Walk a link tree of 300 items, validate a whole selection, build a report: one round trip instead of hundreds of REST calls from the browser.
The full Polarion Java API Everything the tracker, project, security and document services offer, including what the REST API does not expose.
Server-side integration Call external systems from the server, with credentials kept in the user account vault, never in the browser.
Your own contract Request and response shapes that fit your UI, instead of assembling JSON:API documents in the view.
The user's identity Calls run as the user identified by the REST token. Permissions, workflow rules and audit trails apply as in the UI.

How it fits together

  1. Declare the endpoint in manifest.json: a path, a method (GET or POST) and the script file. Declare endpoints →
  2. Write the script in server-scripts/. It reads parameters from arguments, uses context.scriptContext() to reach Polarion, and evaluates to the response object. Write the server script →
  3. Call it from the view with fetch() at context.appEndpoint + '/<path>', sending context.restToken in the required X-Polarion-REST-Token header. Call endpoints from a view →

Polarion takes care of routing, authentication, parameter parsing, JSON serialization and the response envelope.

Every endpoint request requires a valid X-Polarion-REST-Token header, for both GET and POST. A logged-in browser session or session cookie does not authenticate an endpoint call. Opening an endpoint URL in the address bar does not send the required header; use fetch() or an HTTP client that can set it. See Test and debug.

When to write an endpoint, when to use the REST API

Use the Polarion REST API directly from the view when it covers the job: reading and writing single objects, lists with queries, standard relationships. Write an endpoint when you need aggregation, rules, Java-only APIs, server-side secrets, or simply a cleaner contract for your UI. Most real applications do both. REST API or your own endpoints? →

In this section

Worked examples: Traceability with endpoints (a GET that computes a tree, a POST that writes) and Release checklist (validation and bulk update of a selection).

Your own REST endpoints

Declare endpoints

Endpoints are declared in manifest.json under serverScripts.endpoints. Each entry maps an HTTP method and a path segment to a script file in the server-scripts/ folder of the package.

manifest.json (excerpt)
{
  "identifier": "com.example.releasechecklist",
  "…": "…",
  "serverScripts": {
    "endpoints": [
      { "urlPath": "validate",     "method": "POST", "script": "validate.js" },
      { "urlPath": "assign-to-me", "method": "POST", "script": "assign-to-me.js" },
      { "urlPath": "stats",        "method": "GET",  "script": "stats.js" }
    ]
  }
}
Field Meaning
urlPath Last path segment of the endpoint URL. Letters, digits and hyphens; lower-case by convention. Unique per method.
method GET or POST.
script File name inside server-scripts/. Keep one script per endpoint.

The URL

Every endpoint lives under the application's endpoint base, which the framework hands to views as context.appEndpoint:

https://<host>/polarion/apps/<identifier>/rest/<urlPath>

For com.example.releasechecklist the three endpoints above are:

POST https://<host>/polarion/apps/com.example.releasechecklist/rest/validate
POST https://<host>/polarion/apps/com.example.releasechecklist/rest/assign-to-me
GET  https://<host>/polarion/apps/com.example.releasechecklist/rest/stats?objectId=test

The identifier namespaces your endpoints; two applications can both declare validate without conflict.

GET or POST

GET POST
Parameters query string (?objectId=test/TEST-514&depth=2) Flat JSON object in the body ({"objectId": "test/TEST-514", "text": "…"}), Content-Type: application/json
Reading them in the script arguments.getAsString('objectId') arguments.getAsString('text'); every value must be a string. Send lists and objects JSON-encoded in a string and JSON.parse them in the script.
Use for reads, computations, reports writes, anything with side effects, requests with structured or long input
Cacheable by the browser yes (add a cache-busting parameter if that is unwanted) no

Rules of thumb:

The objectId parameter

Every endpoint call must carry a parameter named objectId, in the query string for GET and in the body for POST. Polarion rejects a call without it before the script runs, with HTTP 400 and Argument objectId is missing in workflow definition. Use the id of the object the call is about in the form PROJECT/WI-ID (for example drivepilot/DP-477); a project id alone is also accepted. Your script reads it like any other parameter.

GET  …/rest/linked-tree?objectId=drivepilot/DP-477&depth=2
POST …/rest/validate      {"objectId": "drivepilot/DP-461", "objectIds": "[\"drivepilot/DP-461\",\"drivepilot/DP-527\"]"}

Authentication

Every GET and POST call must send a valid REST token in the X-Polarion-REST-Token header. From a view, use context.restToken:

X-Polarion-REST-Token: <context.restToken>

A browser session or session cookie cannot replace this header. Requests without a valid token are rejected before the script runs, even when the caller is logged in to Polarion. The script executes as the user identified by the token; see Security model.

Package layout

Upload validation checks that every script exists. Scripts are read from the uploaded package; changing them means re-uploading the application, which takes effect immediately.

Versioning your contract

Views and endpoints ship together in one package, so they are always in sync; there is no need for URL versioning between them. If other clients (automation, another application) call your endpoints, treat the request and response shapes as a public contract: add fields rather than renaming them, and document them in the application's README as the examples do.

Your own REST endpoints

Write the server script

An endpoint is implemented by one JavaScript file in server-scripts/. Polarion executes it with GraalVM JavaScript on the server when the endpoint is called, using the same scripting bridge that workflow functions and scheduled scripts use.

The shape of a script

server-scripts/stats.js
// Globals provided by Polarion:
//   context   – entry point to the Polarion API
//   arguments – the request parameters (IArguments)
const trackerService = context.scriptContext().services().tracker();
const scriptArguments = arguments;   // inside functions, `arguments` means something else
let result = {};

// Reads a parameter that may be absent (getAsString throws for missing ones).
function optionalParam(name, fallback) {
  try {
    const value = scriptArguments.getAsString(name);
    return value === null || value === undefined || String(value) === '' ? fallback : String(value);
  } catch (e) {
    return fallback;
  }
}

try {
  // objectId is sent on every call; here it carries the project id.
  const projectId = scriptArguments.getAsString('objectId');
  const limit = parseInt(optionalParam('limit', '50'), 10);
  const project = trackerService.getTrackerProject(projectId);
  // … compute …
  result = { projectId: project.getId(), name: project.getName(), limit: limit };
} catch (e) {
  // An `error` key turns the response into an error response.
  result = { error: 'stats failed: ' + e };
}

result;   // the last expression is the response

Five conventions matter:

  1. Read input from arguments. arguments.getAsString('name') returns the parameter as a string and throws when the parameter was not sent (see rule 5). For POST, the fields of the JSON body are the parameters. Polarion accepts only string values in the body; a nested array or object is rejected before the script runs. Send structured input JSON-encoded in a string and JSON.parse it in the script.
  2. Wrap the body in try/catch and put the message into an error property. Uncaught exceptions also produce an error response, but a message you wrote is easier to act on in the view.
  3. End with the result expression. Whatever the last statement evaluates to is serialized as JSON and wrapped in the response envelope.
  4. Capture arguments at the top level. Inside a JavaScript function, arguments is the function's own arguments object, not Polarion's. Assign const scriptArguments = arguments; at the top of the script and use that in helper functions; otherwise you get arguments.getAsString is not a function.
  5. Guard optional parameters. arguments.getAsString('name') throws Argument name is missing in workflow definition when the parameter was not sent, and the whole call fails with HTTP 400. Read optional parameters through a small helper that catches that case (see optionalParam() in the traceability script below).

The context global

context.scriptContext() returns the script context. Its two entry points:

Expression Returns
context.scriptContext().services() The Polarion services: tracker() (work items, projects, links), security() (current user, permissions), project() (users, projects) and others listed in IScriptServices.
context.scriptContext().utils() Utilities, for example httpClient() for outbound HTTP.

The most used service is the tracker:

const trackerService = context.scriptContext().services().tracker();
const wi = trackerService.getWorkItem('test', 'TEST-514');   // IWorkItem
wi.getTitle(); wi.getStatus().getName(); wi.getDescription();
const project = trackerService.getTrackerProject('test');     // ITrackerProject

The API is Polarion's Java API. The javadoc on your server (https://<host>/polarion/sdk/doc/javadoc/, package com.polarion.alm.tracker.model) documents IWorkItem, ITrackerProject, ILinkedWorkItemStruct, IComment and the rest; the scripting API documentation (sdk/doc/scripting-api/) documents IScriptContext, IScriptServices and IArguments.

Working with Java objects from JavaScript

A GET script that computes

The traceability example walks the link structure of a work item and returns a nested tree in one response:

examples/traceability/server-scripts/linked-tree.js
// GET /polarion/apps/com.example.traceability/rest/linked-tree?objectId=PROJECT/WI-ID&depth=2[&role=implements]
//
// Runs on the Polarion server (GraalVM JavaScript) as the logged-in user.
// Walks the work item links in both directions and returns a nested tree.
// The optional `role` filter applies to links in both directions.
//
// Globals provided by Polarion:
//   context   – IScriptContext access: context.scriptContext().services().tracker()
//   arguments – IArguments: request parameters (query string for GET, JSON body for POST)

const trackerService = context.scriptContext().services().tracker();
let result = {};

// Polarion's IArguments throws ("Argument <name> is missing in workflow definition")
// when a parameter is absent. Optional parameters are therefore read through a guard.
const scriptArguments = arguments;
function getOptionalParam(name, defaultValue) {
  try {
    const value = scriptArguments.getAsString(name);
    return value === null || value === undefined || String(value) === '' ? defaultValue : String(value);
  } catch (e) {
    return defaultValue;
  }
}

function readParameters() {
  const objectId = scriptArguments.getAsString('objectId');
  if (!objectId) {
    throw new Error('objectId parameter is required (PROJECT/WI-ID)');
  }
  const depth = Math.min(3, Math.max(1, parseInt(getOptionalParam('depth', '2'), 10) || 2));
  const roleParam = getOptionalParam('role', '');
  const roleFilter = roleParam ? String(roleParam).trim().toLowerCase() : '';
  return { objectId, depth, roleFilter };
}

function findWorkItem(objectId) {
  const [projectId, workItemId] = objectId.split('/');
  const workItem = trackerService.getWorkItem(projectId, workItemId);
  if (workItem.isUnresolvable()) {
    throw new Error('Work item not found: ' + objectId);
  }
  return workItem;
}

/** Suspect flag of a link; defaults to false if the API call is unavailable. */
function isSuspect(link) {
  try {
    return link.isSuspect() === true;
  } catch (e) {
    return false;
  }
}

/** Id, name and opposite name of a link role, e.g. "verifies", "verifies", "is verified by". */
function roleInfo(link) {
  const role = link.getLinkRole();
  if (!role) return { id: '', name: '', oppositeName: '' };
  let oppositeName = '';
  try {
    oppositeName = role.getOppositeName() ? String(role.getOppositeName()) : '';
  } catch (e) {
    // Without an opposite name the filter matches the id and the name only.
  }
  return { id: String(role.getId()), name: String(role.getName()), oppositeName: oppositeName };
}

// Every role met while walking, so the view can offer them in its filter.
const rolesSeen = new Map();
function remember(info) {
  if (info.id && !rolesSeen.has(info.id)) {
    rolesSeen.set(info.id, info);
  }
}

/**
 * True when no role filter is set or the link role matches it (case-insensitive).
 * The filter compares the role id, its name and its opposite name, so "verifies" also
 * matches a back link that reads "is verified by" from this side.
 */
function roleMatches(info, roleFilter) {
  if (!roleFilter) return true;
  return [info.id, info.name, info.oppositeName].some((value) => value.toLowerCase() === roleFilter);
}

function toTreeNode(workitem) {
  return {
    id: workitem.getProjectId() + '/' + workitem.getId(),
    title: workitem.getTitle(),
    type: workitem.getType() ? workitem.getType().getName() : null,
    status: workitem.getStatus() ? workitem.getStatus().getName() : null,
  };
}

// Direct links ("this item implements X") become the downstream children.
// `ancestors` holds the items on the path from the root to here. Each branch gets its own
// copy, so a cycle stops the recursion but an item reached on two paths is expanded on both.
function buildDownstreamNodes(workitem, depth, ancestors, roleFilter) {
  const workItemId = workitem.getProjectId() + '/' + workitem.getId();
  if (depth <= 0 || ancestors.has(workItemId)) {
    return [];
  }
  const path = new Set(ancestors);
  path.add(workItemId);

  const downstream = [];
  // Java collections are easiest to iterate as arrays from GraalVM JavaScript.
  const direct = workitem.getLinkedWorkItemsStructsDirect().toArray();
  for (let i = 0; i < direct.length; i++) {
    const link = direct[i];
    const info = roleInfo(link);
    remember(info);
    if (!roleMatches(info, roleFilter)) {
      continue;
    }
    const linkedWorkItem = link.getLinkedItem();
    const node = toTreeNode(linkedWorkItem);
    node.role = info.name;
    node.suspect = isSuspect(link);
    if (depth > 1 && !path.has(node.id)) {
      node.downstream = buildDownstreamNodes(linkedWorkItem, depth - 1, path, roleFilter);
    }
    downstream.push(node);
  }
  return downstream;
}

function buildUpstreamNodes(workItem, roleFilter) {
  const upstream = [];
  const back = workItem.getLinkedWorkItemsStructsBack().toArray();
  for (let i = 0; i < back.length; i++) {
    const link = back[i];
    const info = roleInfo(link);
    remember(info);
    // The role filter applies in both directions: a requirement filtered by "verifies"
    // shows the test cases that verify it, which are back links seen from here.
    if (!roleMatches(info, roleFilter)) {
      continue;
    }
    const node = toTreeNode(link.getLinkedItem());
    // Seen from this item a back link reads in the opposite direction ("is verified by").
    node.role = info.oppositeName || info.name;
    node.suspect = isSuspect(link);
    upstream.push(node);
  }
  return upstream;
}

try {
  const { objectId, depth, roleFilter } = readParameters();
  const workItem = findWorkItem(objectId);

  const rootWorkItemNode = toTreeNode(workItem);
  rootWorkItemNode.downstream = buildDownstreamNodes(workItem, depth, new Set(), roleFilter);
  rootWorkItemNode.upstream = buildUpstreamNodes(workItem, roleFilter);

  result = { item: rootWorkItemNode, roles: Array.from(rolesSeen.values()) };
} catch (e) {
  // An `error` key turns the response into an error response for the caller.
  result = { error: 'linked-tree failed: ' + e };
}

result;

A POST script that writes

Writes follow the same pattern plus save():

examples/traceability/server-scripts/add-comment.js
// POST /polarion/apps/com.example.traceability/rest/add-comment
// Body: { "objectId": "PROJECT/WI-ID", "text": "…" }
//
// Adds a plain-text comment to the work item. Runs as the logged-in user, who
// therefore needs permission to comment on the item.

const trackerService = context.scriptContext().services().tracker();
const Text = Java.type('com.polarion.core.util.types.Text');
let result = {};

try {
  const fullId = arguments.getAsString('objectId');
  const text = arguments.getAsString('text');
  if (!fullId) {
    throw new Error('objectId parameter is required (PROJECT/WI-ID)');
  }
  if (!text || text.trim() === '') {
    throw new Error('text parameter is required');
  }

  const [projectId, workitemId] = fullId.split('/');
  const workitem = trackerService.getWorkItem(projectId, workitemId);
  if (workitem.isUnresolvable()) {
    throw new Error('Work item not found: ' + fullId);
  }

  // createComment(IText text, String title, IComment parent) returns the new
  // IComment. Saving the work item alone does not persist it; save the comment.
  const comment = workitem.createComment(Text.plain(text), 'Traceability app', null);
  comment.save();

  // The id may not be assigned yet right after save; report it when available.
  const commentId = comment.getId();
  result = { ok: true, commentId: commentId ? String(commentId) : null };
} catch (e) {
  result = { error: 'add-comment failed: ' + e };
}

result;

Warning

Keep writes in POST endpoints. Treat GET endpoints as read-only; whether a save in a GET script is rejected depends on the server configuration.

Results and the envelope

Polarion wraps the result:

{ "timestamp": "2026-10-05T10:15:42.945Z", "success": true, "data": { "…": "…" } }

With an error key, or after an uncaught exception:

{ "timestamp": "…", "success": false, "error": "stats failed: Error: projectId parameter is required" }

Return plain objects, arrays, strings, numbers and booleans. Do not return Java objects; map them to plain data first (describe(wi) in the example above).

Permissions

The script runs as the user who called the endpoint. trackerService.getWorkItem() on an item the user may not read fails exactly as it would in the UI, and save() is subject to the user's permissions and the workflow. Validate all input: arguments is data from the browser. See Security model.

Secrets and external calls

Never embed credentials in a script. Read them from the user account vault through the services, and perform outbound HTTP with context.scriptContext().utils().httpClient(). The reference application tsapp-1 contains a script that posts an Adaptive Card to Microsoft Teams this way.

Note

The scripts shown in this guide were executed against a Polarion 2612 server. When your server version differs, verify method names against its javadoc.

Your own REST endpoints

Call endpoints from a view

The context gives a view everything it needs to call the application's endpoints: appEndpoint (the base URL) and restToken (the authentication token). The rest is fetch().

Every GET and POST request must send a valid context.restToken in the X-Polarion-REST-Token header. The browser's Polarion session and cookies do not authenticate endpoint calls. If the token is empty, enable REST token authentication before calling endpoints.

The helper

src/polarion.ts
import type { PolarionContext } from 'polarion-app-sdk';

/** Envelope that Polarion wraps around every server-script response. */
interface Envelope<T> {
  timestamp?: string;
  success?: boolean;
  error?: string;
  data?: T;
}

/**
 * Calls one of the application's own endpoints declared in
 * manifest.json under `serverScripts.endpoints`.
 *
 * `context.appEndpoint` is the absolute base URL of those endpoints, for example
 * `https://host/polarion/apps/com.example.traceability/rest` (no trailing slash), so `path`
 * starts with a slash, as in `restFetch`: `"/validate"`. The same
 * `X-Polarion-REST-Token` header as for the REST API authenticates the call.
 * The response envelope is unwrapped so callers only see the script's result.
 */
export async function endpointFetch<T>(context: PolarionContext, path: string, init: RequestInit = {}): Promise<T> {
  const headers = new Headers(init.headers);
  headers.set('X-Polarion-REST-Token', context.restToken ?? '');
  headers.set('Accept', 'application/json');
  if (init.body !== undefined && !headers.has('Content-Type')) {
    headers.set('Content-Type', 'application/json');
  }

  const response = await fetch(`${context.appEndpoint}${path}`, { ...init, headers });

  // Script errors come back as HTTP 400 with the envelope, so parse the body
  // whenever it is JSON and surface the script's own message.
  const text = await response.text();
  let envelope: Envelope<T> | undefined;
  try {
    envelope = JSON.parse(text) as Envelope<T>;
  } catch {
    envelope = undefined;
  }
  if (envelope && (envelope.success === false || envelope.error)) {
    throw new Error(envelope.error ?? 'Server script reported an error.');
  }
  if (!response.ok || !envelope) {
    throw new Error(`Endpoint ${response.status}: ${text}`);
  }
  return envelope.data as T;
}

The helper does four things: builds the URL from appEndpoint, sets the X-Polarion-REST-Token header, sets Content-Type: application/json when there is a body, and unwraps the envelope. Script errors arrive as HTTP 400 with the envelope, so the helper parses the body on every status and throws an Error with the script's own message when success is false.

endpointFetch is the counterpart of restFetch from Calling the REST API from a view: the same arguments, a path that starts with /, and the same token header. The examples keep both in src/polarion.ts under these two names.

GET with query parameters

import type { PolarionContext } from 'polarion-app-sdk';
import { endpointFetch } from './polarion';

interface LinkedTreeResult { item: TreeNode }

async function loadTree(context: PolarionContext) {
  const params = new URLSearchParams({
    objectId: `${context.projectId}/${context.workItemId}`,   // required on every call
    depth: '2',
  });
  return endpointFetch<LinkedTreeResult>(context, `/linked-tree?${params}`);
}

URLSearchParams encodes slashes and spaces correctly.

POST with a JSON body

interface ValidateResult {
  results: { id: string; title: string; status: string; findings: { code: string; message: string }[] }[];
  summary: { items: number; withFindings: number; byCode: Record<string, number> };
}

async function validate(context: PolarionContext, objectIds: string[]) {
  return endpointFetch<ValidateResult>(context, '/validate', {
    method: 'POST',
    // objectId is required on every call; the body must be a flat object with
    // string values, so the list is encoded as a JSON string.
    body: JSON.stringify({ objectId: objectIds[0], objectIds: JSON.stringify(objectIds) }),
  });
}

Polarion parses the POST body as a flat object of string parameters. A nested array or object is rejected with HTTP 500 (Expected a string but was BEGIN_ARRAY) before the script runs. Encode structured input as a JSON string and parse it in the script with JSON.parse(arguments.getAsString('objectIds')).

Types for your contract

Declare the request and response shapes once in src/types.ts and use them in both the helper calls and the components. Because view and endpoint ship together, the TypeScript types are the documentation of the contract; keep them next to the script that implements it.

Handling the outcome

try {
  const result = await validate(context, ids);
  setResults(result.results);
} catch (e) {
  setError(e instanceof Error ? e.message : String(e));
}

Three kinds of failure reach the catch:

Failure Message
HTTP error before the script ran (unknown endpoint, missing token, bad content type, non-string body value) Endpoint 404: …, Endpoint 401: …, Endpoint 400: …, Endpoint 500: {"error":"… Expected a string but was BEGIN_ARRAY …"}
The script returned { error } or threw (HTTP 400 with the envelope) the script's message, for example validate failed: Error: objectIds: expected "PROJECT/WI-ID", got "DP-461"
Network problem the browser's fetch error

Show the message; for 401, call fetchContext() again to refresh the token and retry once.

Loading state and cancellation

Endpoint calls can take longer than REST reads because they do more work. Show a loading state ("Computing the link tree on the server…") and, in views that react to selection changes, debounce calls and ignore stale responses:

useEffect(() => {
  let cancelled = false;
  const timer = setTimeout(() => {
    validate(context, ids).then((r) => { if (!cancelled) setResults(r.results); });
  }, 200);
  return () => { cancelled = true; clearTimeout(timer); };
}, [context, ids]);

Calling endpoints from outside a view

Other clients must also send a valid REST token in the X-Polarion-REST-Token header. Session cookies and personal access tokens sent as Authorization: Bearer are not substitutes. Do not assume that an authentication method accepted by the standard REST API is accepted by application endpoints. See Test and debug for an HTTP client example.

Your own REST endpoints

Patterns

This page collects the shapes that endpoint-backed applications take in practice. Each pattern names the problem, sketches the script and says what the view does with the result.

1. Aggregation: one request instead of many

Problem. The view needs data from many objects: the link tree of a work item, all test cases of a requirement with their last result, the work items of a plan with their time records.

Script. Walk the objects on the server and return a compact structure shaped for the UI.

const trackerService = context.scriptContext().services().tracker();
let result = {};
try {
  const [projectId, wiId] = arguments.getAsString('objectId').split('/');
  const wi = trackerService.getWorkItem(projectId, wiId);
  const links = wi.getLinkedWorkItemsStructsDirect().toArray();
  const children = [];
  for (let i = 0; i < links.length; i++) {
    const target = links[i].getLinkedItem();
    children.push({ id: target.getId(), title: target.getTitle(), role: links[i].getLinkRole().getName() });
  }
  result = { id: wi.getId(), children: children };
} catch (e) {
  result = { error: 'aggregate failed: ' + e };
}
result;

View. One endpointFetch, then render. See Traceability with endpoints.

2. Validation and rules

Problem. Check a set of work items against rules that need several fields, links or history: "every requirement has a test", "no open item older than 90 days without an assignee".

Script. Accept a list of ids (POST), evaluate the rules, return findings per item plus a summary. Keep rule code in small functions so that adding a rule is one function and one entry in a list.

const rules = [
  { code: 'no-description', check: (wi) => !wi.getDescription() || wi.getDescription().getContent().trim() === '' },
  { code: 'unassigned', check: (wi) => wi.getAssignees().isEmpty() },
];

View. A sidebar that validates the selection as it changes and offers fixes. See Release checklist.

3. Bulk writes with a clear outcome

Problem. Apply the same change to many items: assign, set a field, add a link, transition the workflow.

Script. POST with the ids (as a JSON string, plus the mandatory objectId) and the change; loop, save() each item, collect successes and failures instead of aborting on the first error.

const updated = [], failed = [];
for (const fullId of ids) {
  try {
    const [p, id] = fullId.split('/');
    const wi = trackerService.getWorkItem(p, id);
    wi.addAssignee(user);
    wi.save();
    updated.push(fullId);
  } catch (e) {
    failed.push({ id: fullId, error: String(e) });
  }
}
result = { updated: updated, failed: failed };

View. Report both lists; re-run the read afterwards. The REST API can also do bulk updates, but an endpoint gives one round trip and a single, tailored result.

4. External systems with server-side secrets

Problem. Notify a chat channel, create a ticket in another tool, fetch data from an internal service that must not be reachable from the browser.

Script. Read the secret from the user account vault, call the system with context.scriptContext().utils().httpClient(), return a summary.

const httpClient = context.scriptContext().utils().httpClient();
const HttpRequest = Java.type('java.net.http.HttpRequest');
const BodyPublishers = Java.type('java.net.http.HttpRequest$BodyPublishers');
const URI = Java.type('java.net.URI');
// const webhook = <read from the vault>;
const request = HttpRequest.newBuilder(URI.create(webhook))
  .header('Content-Type', 'application/json')
  .POST(BodyPublishers.ofString(JSON.stringify(card)))
  .build();
const response = httpClient.sendRequest(request);

View. A button and a status line. The reference application tsapp-1 contains a complete Teams notification script.

5. Computed data for dashboards

Problem. A navigation topic needs counts, trends or groupings over the whole project.

Script. Query with the tracker service, aggregate in a loop, return the numbers. Add parameters for the query and the grouping so that one endpoint serves several widgets.

View. Render tiles and charts; refresh on demand. Combine with the REST API for the detail table below the charts.

6. Configuration without an administration view

Problem. The application needs settings (a mapping table, thresholds, a target URL) until administration views arrive.

Script. A GET endpoint reads the settings from a known place: a document in a configuration space, a work item of a dedicated type, or a JSON file in the global configuration repository. A POST endpoint writes them, checking that the caller is an administrator through the security service.

View. A small settings form in a navigation topic, visible only to administrators.

7. Caching expensive results

Endpoints hold no state between calls. For results that are expensive and change rarely:

Anti-patterns

Your own REST endpoints

Test and debug

Endpoints are plain HTTP. Every test request must include a valid X-Polarion-REST-Token header; a browser session alone does not authenticate the request.

Call a GET endpoint from the developer tools

With an application view open in Polarion, select the view's frame in the browser console. Use the context fetched by your view to set the token header:

const params = new URLSearchParams({ objectId: 'test/TEST-514', depth: '1' });
const r = await fetch(`${ctx.appEndpoint}/linked-tree?${params}`, {
  headers: { 'X-Polarion-REST-Token': ctx.restToken, Accept: 'application/json' },
});
console.log(await r.json());

ctx is the context your view fetched. Opening the URL directly in a new tab does not send this header and cannot authenticate the request. An authenticated call returns the raw envelope:

{"timestamp":"2026-10-05T10:15:42.945Z","success":true,"data":{"item":{…}}}

Call any endpoint from the developer tools

With a view open in Polarion, the context is in memory. In the browser console, select the view's frame and run:

const r = await fetch(`${ctx.appEndpoint}/validate`, {
  method: 'POST',
  headers: { 'X-Polarion-REST-Token': ctx.restToken, 'Content-Type': 'application/json' },
  body: JSON.stringify({ objectId: 'test/TEST-514', objectIds: JSON.stringify(['test/TEST-514']) }),
});
console.log(await r.json());

ctx is the context your view fetched; expose it on window in development builds if that is convenient.

Call from an HTTP client with a REST token

For a diagnostic call with curl, supply a current REST token as POLARION_REST_TOKEN in your local shell. Use the token provided to the view as context.restToken; keep it out of saved scripts, logs and version control:

curl -s -X POST "https://<host>/polarion/apps/com.example.releasechecklist/rest/validate" \
  -H "X-Polarion-REST-Token: $POLARION_REST_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"objectId":"test/TEST-514","objectIds":"[\"test/TEST-514\"]"}'

Application endpoints require this header. A session cookie or an Authorization: Bearer personal access token does not replace it. Do not assume that authentication methods supported by the standard REST API also authenticate application endpoints.

Reading errors

What you see Where it comes from What to do
success: false, error: "… failed: Error: objectId parameter is required" Your own throw inside try/catch The view did not send the parameter, or sent it in the wrong place (query string vs body).
HTTP 400, error: "Argument objectId is missing in workflow definition." The call did not include objectId Add objectId=PROJECT/WI-ID to every call.
HTTP 400, error: "… Argument role is missing in workflow definition." arguments.getAsString() for a parameter that was not sent Send the parameter or read it through a guarded helper.
error: "… TypeError: arguments.getAsString is not a function" arguments used inside a function Capture const scriptArguments = arguments; at the top of the script.
success: false, error: "… TypeError: wi.getFoo is not a function" A Java method name that does not exist Check the javadoc for the class; Java methods are case-sensitive and need parentheses.
success: false, error: "… java.lang.SecurityException …" or a permission message The user may not perform the operation Expected for users without rights; show it.
HTTP 400 before any envelope Request shape (missing JSON content type or body on POST) Set Content-Type: application/json and send a JSON body, {} if empty.
HTTP 401 Missing, invalid or expired X-Polarion-REST-Token Send the header with a valid token; refresh the context and check that token authentication is enabled. A logged-in browser session is insufficient.
HTTP 404 Wrong urlPath, wrong method, or application not installed Compare with the manifest and Properties.

The server log

Uncaught exceptions and the output of console.log() in scripts are expected in Polarion's main log (data/logs/main/log4j-*.log). Prefix log lines with the application identifier so that they can be filtered.

Iterating on a script

  1. Edit the script in server-scripts/.
  2. npm run package (the view does not need to change; the script is just copied).
  3. Upload. The new script is active immediately.
  4. Repeat the call.

For faster iteration on logic that does not depend on request parameters, the Scripting topic in Global Administration can run GraalVM scripts interactively against the same services; move the code into the endpoint once it works.

Checklist before shipping an endpoint

Concepts

Application package

An application package is a ZIP file. Polarion validates its structure during upload, unpacks it, and serves its content.

Layout

Rules that Polarion checks:

A ZIP that puts manifest.json at the root, or that nests the application one level deeper, fails with Application's zip structure is incorrect.

Validation and limits

On every upload and update, Polarion checks the ZIP against limits that protect the server. A package that exceeds one of them is rejected as a whole.

Check Default limit Global configuration property
Directory depth 10 levels inside the ZIP polarionapp.directoryDepthLimit
Number of entries 1,000 files and folders polarionapp.maxNumberOfEntries
Size of one entry 10 MB per file, unpacked polarionapp.entrySizeLimitMB
Total size 30 MB, unpacked polarionapp.totalSizeLimitMB
Length of an entry name 128 characters polarionapp.entryNameLengthLimit
Length of the ZIP file name 64 characters polarionapp.zipFileNameLengthLimit

A typical view built with Vite stays far below these limits: the example applications in this guide have 4 to 8 files and about 250 KB unpacked.

To change a limit, set the property in the global configuration:

  1. Log in as a user with global administration rights.
  2. Open Global Administration (avatar menu → Global Administration, or the wrench icon).
  3. Open Configuration Properties at the bottom of the administration navigation.
  4. Add the property to Current Configuration, for example:

    polarionapp.totalSizeLimitMB=50
    
  5. Save and reload the browser page.

Allowed file types

A package may contain only static web assets and images. Polarion checks the extension and the content type of every file; if one file is not on the list below, the whole package is rejected.

Category Extensions Accepted MIME types
Web pages .html, .htm text/html, application/xhtml+xml, text/plain
Stylesheets .css text/css, text/plain
Scripts .js text/javascript, application/javascript, text/plain
Data and configuration .json application/json, text/x-json, text/plain
Raster images .png image/png
.jpg, .jpeg, .jpe image/jpeg
.gif image/gif
.webp image/webp
.ico image/x-icon
Vector images .svg image/svg+xml

Server scripts are .js files and therefore allowed. Executable and back-end formats such as .java, .py, .php, .sh or .exe are never accepted; this prevents remote code execution through an uploaded package.

Some build outputs are not on the list and have to stay out of the package:

The manifest

manifest.json has three parts: identity, views and server scripts.

manifest.json
{
  "manifestVersion": "1.0",
  "identifier": "com.example.inspector",
  "title": "Work item inspector",
  "description": "Shows details and links of the selected work items.",
  "publisherName": "Example Publisher",
  "applicationVersion": "1.2.0",
  "views": {
    "formExtensions": [
      { "identifier": "card", "title": "Inspector", "rootDirectory": "card", "document": "index.html" }
    ],
    "sidebars": [
      { "identifier": "sidebar", "title": "Inspector", "rootDirectory": "sidebar", "document": "index.html",
        "menuIcon": "icon16.png", "icon": "icon32.png" }
    ],
    "navigationTopics": []
  },
  "serverScripts": {
    "endpoints": [
      { "urlPath": "linked-tree", "method": "GET", "script": "linked-tree.js" },
      { "urlPath": "add-comment", "method": "POST", "script": "add-comment.js" }
    ]
  }
}

Every field is described in the manifest.json reference.

Identifiers and what they become

The application identifier and the view identifiers are combined into several other names. Choosing them well avoids renaming later.

Name Built from Example
Static file URL identifier, rootDirectory /polarion/apps/com.example.inspector/card/index.html
View entry URL identifier, view identifier /polarion/apps/com.example.inspector/views/card
Endpoint URL (appEndpoint) identifier, urlPath /polarion/apps/com.example.inspector/rest/linked-tree
Configuration id (applicationView id) identifier + . + view identifier com.example.inspector.card
Sidebar URL parameter polarion-application. + configuration id ?sidebar=polarion-application.com.example.inspector.sidebar
Navigation topic URL project URL + configuration id /polarion/#/project/test/com.example.inspector.overview

Recommendations:

Views are static sites

A view folder is a self-contained static web site. Polarion does nothing to its content beyond serving it; there is no server-side templating or injection. Consequences:

Server scripts folder

Scripts in server-scripts/ are not served as static files. They are executed on the server when their endpoint is called. See Your own REST endpoints.

Size and content

Keep packages small: a typical React view is a few hundred kilobytes. Large media files belong on a separate server. The limits and the allowed file types are listed in Validation and limits and Allowed file types. Polarion stores the unpacked package itself; nothing is placed in the extensions/ folder and no restart is needed.

Concepts

Application context

When Polarion embeds a view, the view starts with no knowledge of its surroundings. The context is the answer to "where am I?": which application and view this is, which project, which work item or document, what is selected, and how to call back into Polarion.

Obtaining the context

import { fetchContext } from 'polarion-app-sdk';

const context = await fetchContext();

fetchContext() sends a request to the Polarion host page and resolves with a PolarionContext object. It rejects with an error if no answer arrives within five seconds, which is what happens when the page is not embedded by Polarion.

Call it once when the view starts. It is safe to call it again later; the answer reflects the state at that moment.

The object

interface PolarionContext {
  applicationId: string;        // "com.example.inspector"
  viewId: string;               // "card"

  projectId?: string;           // "test"
  spaceId?: string;             // "_default"      (Document views)
  documentId?: string;          // "Requirements"  (Document views)
  workItemId?: string;          // "TEST-514"      (form extensions)
  selectedWorkItemIds: string[];// ["test/TEST-514"] in a form (all ticked items in a multi-item edit form); empty in sidebars

  appEndpoint: string;          // "https://host/polarion/apps/com.example.inspector/rest"
  restBaseUrl: string;          // "https://host/polarion/rest/v1"
  restToken?: string;           // token for the X-Polarion-REST-Token header
}

A real example, captured from a form extension (names shortened):

{
  "applicationId": "com.example.context",
  "viewId": "form",
  "projectId": "test",
  "workItemId": "TEST-514",
  "selectedWorkItemIds": ["test/TEST-514"],
  "appEndpoint": "https://polarion.example.com/polarion/apps/com.example.context/rest",
  "restBaseUrl": "https://polarion.example.com/polarion/rest/v1",
  "restToken": "UE9M…"
}

The field-by-field description is in the PolarionContext reference.

What is set where

Field Form extension Sidebar (table) Sidebar (document) Navigation topic
projectId ✔ ✔ ✔ ✔
workItemId ✔ – – –
spaceId, documentId only inside a Document – ✔ –
selectedWorkItemIds the open item; all ticked items in the multi-item edit form empty empty empty
restBaseUrl, appEndpoint ✔ ✔ ✔ ✔
restToken ✔ when token auth is enabled ✔ ✔ ✔

In the multi-item edit form below the Work Items table, opened by ticking several rows, a form extension gets all ticked items in selectedWorkItemIds (for example ["drivepilot/DP-477", "drivepilot/DP-461", "drivepilot/DP-393"]), while workItemId is the current item (DP-477). Observed on Polarion 2612.

The selection in a sidebar does not come from the context: on Polarion 2612 selectedWorkItemIds is empty in a sidebar even when rows are selected, also when the context is read again. The selection arrives through selection-changed events; see React to selection changes. The Application context example shows the empty selectedWorkItemIds in a sidebar; the Selection sidebar example follows the selection with events.

Write code that tolerates missing optional fields. A form extension that is also declared as a navigation topic, for instance, must handle workItemId being undefined.

Work item identifiers

workItemId is a project-local identifier such as TEST-514. The entries of selectedWorkItemIds and of the selection-changed event, in contrast, carry the project: test/TEST-514. Both forms were observed on Polarion 2612, in a form extension, the Work Items table and a Document. Code that accepts both is safest: add the project when an id has no /, strip it where the REST API expects the local id. The REST API addresses work items as projectId/workItemId in resource ids and as separate path segments in URLs; server script examples in this guide use the combined form "test/TEST-514" in an objectId parameter. Build those strings from projectId and the local id:

const fullId = `${context.projectId}/${context.workItemId}`;

The context is a snapshot

The context is static. The host answers fetchContext() with the state at the time of the call, and nothing in the object changes while the view is open; reading it again returns the same kind of snapshot, not a live view. For anything that changes while the view is open, use events:

How the token flows

Polarion creates the REST token when it loads a view: the host bridge mints it for the logged-in user and hands it over in the context. That is why a server without token authentication shows the warning X-Rest-Token generation is not allowed on the server at the moment a view opens, and why restToken is empty there. A fresh token is issued on every view load. Calls to the application's own endpoints require this token in the X-Polarion-REST-Token header. The Polarion session alone does not authenticate those calls, so they cannot be tested by opening the URL in the browser's address bar.

The token is a credential

restToken grants the current user's rights to anyone who holds it. Keep it in memory, send it only to restBaseUrl and appEndpoint on the same origin, and never log it, store it or forward it to third parties. See Security model.

Concepts

REST API or your own endpoints?

A view reaches Polarion data in two ways. Both are authenticated with the same token from the context, both run as the logged-in user, and most applications use both. This page helps you decide which one to use for a given task; the SDK (context and events) is the third channel and is covered in How an application works.

Side by side

Polarion REST API Your own endpoints
What it is Polarion's documented API, JSON:API style, under /polarion/rest/v1 HTTP endpoints under /polarion/apps/<identifier>/rest/, implemented by your JavaScript on the server
Code to write Only in the view Script on the server plus the call in the view
Covers Projects, work items, documents, test runs, plans, users, enumerations, … Anything the Polarion Java API can do, plus external systems
Request shape Fixed by the API (sparse fields, includes, pagination) Defined by you
Work per request One resource or one list Unlimited (within reason)
Runs as The user The user
Deployed with Nothing extra The application package
Documentation REST API User Guide, OpenAPI definition on the server Your README and TypeScript types

Use the REST API when…

See Calling the REST API from a view and the Cookbook.

Write an endpoint when…

See Your own REST endpoints and Patterns.

Typical split in an application

Task Channel
Show the open work item's fields REST API
Show its full link tree with status of each node Endpoint
Rename, set a field, add a comment REST API
Validate the selected items against project rules Endpoint
Assign all items with a finding to the current user Endpoint (one call, one result) or REST API (one PATCH per item)
Dashboard counts by status, type, assignee REST API for small projects, endpoint for large ones
Notify a chat channel Endpoint

What is not available in 2612

These are preview limitations; see Limitations and known issues.

Concepts

Security model

This page describes who can install applications, whose permissions views and server scripts run with, and what application authors must take care of.

Installation is an administrative act

Only users with Global Administration rights see the Applications topic and can upload, update or delete applications. There is no per-project installation and no self-service for end users.

Uploading an application means trusting its author: the static files are served to every user who opens a view, and server scripts run on the Polarion server with the Java API available. Treat an application ZIP like any other software you deploy: review it, keep the SHA-2 hash shown during upload with your change records, and only install packages from sources you trust.

Views run in the user's browser as the user

A view is a web page inside Polarion's origin and receives a REST token in the context for the logged-in user. Calls from the view to the REST API and application endpoints must send this token in the X-Polarion-REST-Token header. The token identifies the user, and calls are subject to that user's permissions, workflow rules and license. A view cannot escalate privileges.

Application endpoints do not authenticate requests through the browser session or session cookies. Being logged in to Polarion does not remove the token-header requirement, for either GET or POST requests.

Consequences for authors:

Server scripts run on the server as the user

A server script executes with the identity of the user identified by the endpoint request's REST token. context.scriptContext().services().security() reports that user, and all tracker operations check permissions as usual. A script therefore cannot read data the user could not read in the UI.

Scripts do have server-side capabilities that the browser does not: HTTP access from the server, reading project vault secrets, and the whole Java API. Review scripts carefully for:

Same-origin, iframe isolation

Views are served from the Polarion origin, so the browser's same-origin policy does not separate the view from the host page. Polarion isolates the view in an iframe and defines a narrow message protocol (the host bridge). Stay within that protocol through the SDK; do not reach into window.parent to read or modify the Polarion UI. Such code breaks with every Polarion release and bypasses the design that keeps applications supportable.

The SDK verifies the origin of every message it receives and ignores messages from other origins.

Content Security Policy and external resources

Polarion serves application files with the same HTTP headers as its own UI. If your server enforces a Content Security Policy that blocks external scripts or styles, a view that loads libraries from a public CDN is expected to fail (check the browser console for Refused to load); this was not exercised in this guide. Bundle everything with Vite instead of loading from CDNs; that also avoids the dependency on internet access from the user's browser.

Calls from a view to other origins are subject to CORS on that origin. If your application needs an external service, call it from a server script or make sure the service allows the Polarion origin.

Data protection

Views see personal data (user names, assignees, comments) exactly as the user does. Do not send Polarion data to third-party services from the browser without the same approval you would need for any other integration. Server scripts that forward data (for example to a chat tool) should be limited to what the use case needs.

Checklist for application authors

Concepts

Performance and load

An application runs on a server that a whole organization shares. A form extension loads every time anyone opens a work item of the configured type, a sidebar every time someone opens a table, and each load sends its requests again. Server scripts run in the same Java process as Polarion and read from the same repository, index and database. A slow or chatty application therefore costs more than its own users' time: it slows down Polarion for everybody on the server.

This page collects what keeps an application light. Most of it is ordinary web practice. The Polarion-specific parts are the Lucene and SQL queries and the server scripts.

Rules of thumb

The numbers below are not limits that Polarion enforces. They are reasonable targets for a view that opens automatically with a page. Go beyond them when the use case needs it and you have measured the result.

Target
REST requests when a view opens 1 to 3; never one request per item
Items loaded by a view what it shows, usually up to 100; offer Load more or a search beyond that
Response size under about 100 KB for a view that opens automatically
Debounce on selection changes and typing 150 to 300 ms
Polling none by default; if unavoidable, 60 s or more and only while the view is visible
Server script run time under 1 s for a view that opens automatically, a few seconds for an action the user started
Retries at most one, after a delay, and only for temporary errors

Load only what the view shows

Name the fields. Ask with fields[workitems] for the fields the view shows. Rich-text fields such as description can be large; leave them out unless the view renders them.

// Don't: every field of up to 100 work items, then filtered in the browser.
const all = await restFetch(context, `/projects/${p}/workitems?page[size]=100`);
const open = all.data.filter((w) => w.attributes.status === "open");

// Do: let the server filter, and ask only for the columns the table shows.
const params = new URLSearchParams({
  query: "status:open AND type:task",
  "fields[workitems]": "id,title,status",
  "page[size]": "50",
});
const open = await restFetch(context, `/projects/${p}/workitems?${params}`);

Filter on the server. A Lucene query runs against the index. Filtering in the browser means the server has already read, serialized and sent every item you throw away.

One request for related items. include returns the work item and its linked items in one response. A loop that requests each linked item separately sends N + 1 requests for the same data.

Batch by id. A selection of 40 work items is one request with query=id:(DP-1 DP-2 …), not 40. Split very long id lists into chunks of 100, as the selection sidebar and the release checklist do.

Page, but stop. Walk pages only as far as the user needs. A view that silently reads every page of a 20,000-item project reads 200 pages of 100 items each time it opens.

Search instead of listing. For a user or plan picker, send what the user typed as a query and show the first matches. Loading every user of a large installation into a select list is slow for the server and unusable for the user.

Send fewer requests

useEffect(() => {
  const tick = () => {
    if (document.visibilityState === "visible") void load();
  };
  const timer = setInterval(tick, 60_000);
  return () => clearInterval(timer);
}, [load]);

Errors and retries

A retry loop turns one failed request into many at the moment the server is already struggling.

// Don't: retries forever, immediately, for every kind of error.
while (true) {
  try { return await restFetch(context, url); } catch { /* try again */ }
}

Server scripts

An endpoint script runs inside Polarion with the caller's permissions, and the caller waits until it finishes. See Endpoint runtime.

SQL

Polarion keeps a PostgreSQL database next to its index, and SQL can be faster than Lucene for counting and joining across work items, documents, links and test runs. The same power makes a careless query expensive: it runs on the database every Polarion user depends on.

-- Don't: every column of every work item in every project, joined to all links,
-- filtered by a leading wildcard on the description.
SELECT *
FROM workitem w
LEFT JOIN struct_workitem_linkedworkitems l ON l.fk_uri_p_workitem = w.c_uri
WHERE w.c_description LIKE '%brake%'

-- Do: one project, one type, one link role, EXISTS instead of a join,
-- and only the column Polarion needs to return the objects.
SELECT w.c_uri
FROM workitem w
INNER JOIN project p ON p.c_uri = w.fk_uri_project
  AND p.c_id = 'drivepilot'
WHERE w.c_type = 'requirement'
  AND EXISTS (
    SELECT 1
    FROM struct_workitem_linkedworkitems link
    WHERE link.fk_uri_workitem = w.c_uri
      AND link.c_role = 'verifies'
  )
LIMIT 200

The schema, the join rules and more examples are in the SDK documentation of every installation, at https://<polarion>/polarion/sdk/doc/database/.

Test before production

Checklist

Development guides

Set up the project

This guide describes the layout used by all examples in this documentation. It is a plain Vite project with a manifest.json and a packaging script added. Any other toolchain works as long as the output is a static site with relative URLs.

Single-view application

package.json

package.json
{
  "name": "hello-polarion",
  "private": true,
  "version": "0.1.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc -b && vite build",
    "package": "npm run build && node scripts/package.mjs",
    "preview": "vite preview"
  },
  "dependencies": {
    "polarion-app-sdk": "file:../_sdk/polarion-app-sdk-0.5.2-preview.tgz",
    "react": "^19.2.0",
    "react-dom": "^19.2.0"
  },
  "devDependencies": {
    "@types/node": "^24.10.1",
    "@types/react": "^19.2.5",
    "@types/react-dom": "^19.2.3",
    "@vitejs/plugin-react": "^5.1.1",
    "adm-zip": "^0.5.16",
    "typescript": "~5.9.3",
    "vite": "^7.2.4"
  }
}

Notes:

tsconfig.json

tsconfig.json
{
  "compilerOptions": {
    "target": "ES2022",
    "lib": ["ES2022", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "moduleResolution": "bundler",
    "jsx": "react-jsx",
    "types": ["vite/client"],
    "strict": true,
    "noEmit": true,
    "skipLibCheck": true,
    "verbatimModuleSyntax": true,
    "allowImportingTsExtensions": true
  },
  "include": ["src"]
}

moduleResolution: "bundler" is what lets TypeScript find the SDK's type definitions through the exports field of its package.json.

vite.config.ts

vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  base: './',
});

base: './' is mandatory. Polarion serves the view under /polarion/apps/<identifier>/<rootDirectory>/, and Vite's default absolute /assets/… URLs would point at the Polarion root.

The packaging script

The script in scripts/package.mjs reads manifest.json, stages <identifier>/manifest.json, copies dist/ to <identifier>/<rootDirectory>/ and server-scripts/ if present, and writes <identifier>.zip. It is deliberately small so that you can read and adapt it; see the full listing in Your first application.

Applications with several views

Each view needs its own folder in the package with its own index.html. Two approaches work well.

One Vite project per view

Keep one sub-folder per view, each a complete Vite project, and a top-level manifest.json:

Simple to understand, and each view can use different libraries. Shared code lives in a third folder that both import with a relative path, or in a local npm workspace.

One project, several Vite entries

One package.json, one src/ with a folder per view, and a build script that runs Vite once per view with a mode:

vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { resolve } from 'node:path';

const VIEWS = ['card', 'sidebar'] as const;

export default defineConfig(({ mode }) => {
  const view = (VIEWS as readonly string[]).includes(mode) ? mode : VIEWS[0];
  return {
    plugins: [react()],
    base: './',
    root: resolve(__dirname, 'src', view),       // src/card/index.html, src/sidebar/index.html
    build: { outDir: resolve(__dirname, 'dist', view), emptyOutDir: true },
  };
});
package.json (scripts)
"scripts": {
  "build": "tsc -b && vite build --mode card && vite build --mode sidebar",
  "package": "npm run build && node scripts/package.mjs"
}

The packaging script then copies dist/<view>/ to <identifier>/<view>/ for every view in the manifest. Shared components live in src/shared/. The reference application tsapp-1 uses a variant of this layout.

Avoid Vite's multi-page mode with a shared dist/assets/ folder: the shared assets would sit outside every rootDirectory, and only files inside view folders are guaranteed to be served.

Icons and other static files

Put icons in public/; Vite copies them unchanged to the root of dist/, which becomes the root of the view folder. Reference them in the manifest by file name ("menuIcon": "icon16.png").

Linting and formatting

Nothing Polarion-specific. The reference application uses ESLint with typescript-eslint and the React hooks plugin; the examples here keep the toolchain minimal.

Source control

Commit manifest.json, the sources, package.json and package-lock.json. Ignore node_modules/, dist/, the staging folder and the generated ZIP:

.gitignore
node_modules
dist
package
*.zip

Development guides

Install the SDK

The Polarion Application SDK is the npm package polarion-app-sdk. It is small (one module, no dependencies) and provides the communication layer between your view and the Polarion host page.

Where the package comes from

The SDK is not published to the public npm registry. Every Polarion 2612 server serves the package from its SDK folder:

https://<polarion-host>/polarion/sdk/applications/polarion-app-sdk-0.5.2-preview.tgz

Open https://<polarion-host>/polarion/sdk/applications/ in a browser to see the versions available on your server. Using the package from the server you deploy to guarantees that the SDK and the host bridge speak the same protocol version.

Install from the server URL

npm install https://polarion.example.com/polarion/sdk/applications/polarion-app-sdk-0.5.2-preview.tgz

npm downloads the tarball and records the URL in package.json:

"dependencies": {
  "polarion-app-sdk": "https://polarion.example.com/polarion/sdk/applications/polarion-app-sdk-0.5.2-preview.tgz"
}

Every later npm install (for example in CI) fetches it from the same URL, so the build machine needs HTTPS access to the Polarion server. The server's certificate must be trusted by Node.js; a self-signed certificate makes npm fail with SELF_SIGNED_CERT_IN_CHAIN. In that case either add the CA to NODE_EXTRA_CA_CERTS or use the local file variant below.

Install from a local file

Download the .tgz once and keep it next to the project (or in a shared folder of your repository):

npm install ./polarion-app-sdk-0.5.2-preview.tgz
"dependencies": {
  "polarion-app-sdk": "file:polarion-app-sdk-0.5.2-preview.tgz"
}

The examples in this guide use this variant with the tarball vendored under examples/_sdk/, so that they build without network access.

Import

The package ships ES module and CommonJS builds plus TypeScript declarations. In a Vite project:

import {
  fetchContext,
  events,
  destroy,
  EventTypes,
  type PolarionContext,
  type SelectionChangedData,
} from 'polarion-app-sdk';

Plain JavaScript:

import { fetchContext, events, destroy, EventTypes } from 'polarion-app-sdk';

CommonJS (for tools that still need it):

const { fetchContext, events, destroy, EventTypes } = require('polarion-app-sdk');

What is inside

Only the exports of HostBridge are public API: fetchContext, events, destroy, EventTypes and the types PolarionContext and SelectionChangedData. The gateway and protocol files are internal.

Upgrading

When a server is upgraded, check /polarion/sdk/applications/ for a newer tarball, install it, rebuild and re-upload. The SDK version is printed in package.json of the installed package and in the README.md shipped with it.

Development guides

Read the context

fetchContext() is the first call every view makes. This guide shows the patterns that work well and the mistakes that are easy to make.

Plain JavaScript

import { fetchContext, destroy } from 'polarion-app-sdk';

async function start() {
  try {
    const context = await fetchContext();
    render(context);
  } catch (error) {
    showError('This page must be opened inside Polarion.', error);
  }
}

window.addEventListener('beforeunload', () => destroy());
start();

React

Fetch once on mount, keep the result in state, and release the bridge on unmount:

import { useEffect, useState } from 'react';
import { destroy, fetchContext, type PolarionContext } from 'polarion-app-sdk';

export function usePolarionContext() {
  const [context, setContext] = useState<PolarionContext | null>(null);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    let cancelled = false;
    fetchContext()
      .then((ctx) => {
        if (!cancelled) setContext(ctx);
      })
      .catch((e: unknown) => {
        if (!cancelled) setError(e instanceof Error ? e : new Error(String(e)));
      });
    return () => {
      // Ignore pending results before destroy() cancels requests, including during Strict Mode cleanup.
      cancelled = true;
      destroy();
    };
  }, []);

  return { context, error };
}
export default function App() {
  const { context, error } = usePolarionContext();
  if (error) return <p>Cannot reach Polarion: {error.message}</p>;
  if (!context) return <p>Loading…</p>;
  return <p>Work item {context.workItemId} in {context.projectId}</p>;
}

In React 18/19 development mode with StrictMode, effects run twice: the first run's fetchContext() is canceled by the cleanup's destroy() and rejects, then the second run creates a fresh instance and succeeds. The cancelled flag set in the cleanup makes the hook ignore everything the first run returns, the rejection included, without depending on the wording of the error. Production builds do not double-invoke effects.

Handling the failure case

fetchContext() rejects after five seconds when no host answers. That happens when:

Show a clear message rather than a spinner. Users and administrators who open the view URL to check a deployment should see "this view only works inside Polarion", not a hang.

Deriving identifiers

const { projectId, workItemId, spaceId, documentId } = context;

// REST URL for the open work item
const workItemUrl = `${context.restBaseUrl}/projects/${projectId}/workitems/${workItemId}`;

// Combined id used by server scripts in this guide and as JSON:API resource id
const fullId = `${projectId}/${workItemId}`;

// REST URL for the open document (sidebar in a Document)
const documentUrl = `${context.restBaseUrl}/projects/${projectId}/spaces/${spaceId}/documents/${documentId}`;

// Polarion UI link to a work item, for <a target="_top">
const uiLink = `${window.location.origin}/polarion/#/project/${projectId}/workitem?id=${workItemId}`;

All of these are optional in the type. Guard them according to the view type:

if (!context.workItemId) {
  throw new Error('This view must be placed on a work item form.');
}

Refreshing

The context is a snapshot and does not change while the view is open. Call fetchContext() again when you need a fresh token (after a 401). Reading it again does not give a sidebar the current selection: selectedWorkItemIds stays empty there, and the selection arrives only through selection-changed events. Each call is a round trip to the host page and resolves in a few milliseconds.

Logging

During development it helps to print the context once:

console.log('[myapp] context', context);

Remove or guard such logs before release; the context contains the REST token.

Next

Development guides

React to selection changes

Sidebars live next to a Work Items table or inside a Document, where the user keeps changing what is selected. The SDK delivers those changes as events.

The Selection inspector sidebar following the table selection

The event

import { events, EventTypes, type SelectionChangedData } from 'polarion-app-sdk';

const unsubscribe = events.subscribe<SelectionChangedData>(
  EventTypes.SELECTION_CHANGED,
  (data) => {
    console.log(data.selectedWorkItemIds); // e.g. ["test/TEST-514", "test/TEST-513"]
  },
);

Initial state plus events

On Polarion 2612 the context of a sidebar has an empty selectedWorkItemIds, even when rows are selected; the selection arrives with the first event after the user changes it. Read the context for the project and the token, start with the context's list (empty in a sidebar) and replace it on every event:

const context = await fetchContext();
let selected = context.selectedWorkItemIds;        // empty in a sidebar
const unsubscribe = events.subscribe<SelectionChangedData>(EventTypes.SELECTION_CHANGED, (data) => {
  selected = data.selectedWorkItemIds;             // updates
  render(selected);
});
render(selected);

React pattern

Subscribe in an effect, store the ids in state, and derive everything else from the ids. This is App.tsx of the Selection sidebar example; the components it renders are in Components.tsx on that page:

examples/selection-sidebar/src/App.tsx
import { useEffect, useState } from "react";
import { destroy, events, EventTypes, fetchContext, type PolarionContext, type SelectionChangedData } from "polarion-app-sdk";
import { ErrorMessage, SelectionContent, SelectionSummary } from "./Components";
import { restFetch } from "./polarion";
import type { WorkItemListResponse, WorkItemResource } from "./types";

/** Selection ids may arrive as "WI-1" or "PROJECT/WI-1"; the Lucene query needs the bare id. */
function bareId(id: string): string {
  const separator = id.indexOf("/");
  return separator === -1 ? id : id.slice(separator + 1);
}

function timeNow(): string {
  return new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" });
}

export default function App() {
  const [context, setContext] = useState<PolarionContext | null>(null);
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [items, setItems] = useState<WorkItemResource[]>([]);
  const [lastEvent, setLastEvent] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  // Fetch context and subscribe to selection changes when the view mounts.
  useEffect(() => {
    let cancelled = false;

    const loadContext = async () => {
      try {
        const data = await fetchContext();
        if (cancelled) {
          return;
        }
        setContext(data);
        setSelectedIds(data.selectedWorkItemIds ?? []);
        setError(null);
      } catch (error: unknown) {
        if (cancelled) {
          return;
        }
        console.error("Unable to fetch the Polarion context:", error);
        const message = error instanceof Error ? error.message : String(error);
        setError(`Unable to fetch the Polarion context: ${message}`);
      }
    };
    loadContext();

    const unsubscribe = events.subscribe<SelectionChangedData>(EventTypes.SELECTION_CHANGED, (data) => {
      // The event contains work item IDs (<project_id>/<workitem_id>) only.
      setSelectedIds(data.selectedWorkItemIds ?? []);
      setLastEvent(timeNow());
    });

    return () => {
      // Ignore pending results before destroy() cancels requests, including during Strict Mode cleanup.
      cancelled = true;
      // Remove the subscription and release the message listener.
      unsubscribe();
      destroy();
    };
  }, []);

  // Whenever the context or selection changes, load the selected work item details.
  // The REST API returns at most 100 items per page, so request IDs in batches
  // of up to 100 and combine the results.
  // Wait 150 ms for rapid selection changes to settle and ignore outdated responses.
  useEffect(() => {
    const projectId = context?.projectId;
    if (!context || !projectId || selectedIds.length === 0) {
      setItems([]);
      return;
    }

    let cancelled = false;

    const loadItems = async () => {
      try {
        const pageSize = 100;
        const requests: Promise<WorkItemListResponse>[] = [];

        for (let i = 0; i < selectedIds.length; i += pageSize) {
          const ids = selectedIds.slice(i, i + pageSize).map(bareId);
          const params = new URLSearchParams({
            "query": `id:(${ids.join(" ")})`,
            "fields[workitems]": "id,title,status,type",
            "page[size]": String(pageSize),
          });
          const path = `/projects/${encodeURIComponent(projectId)}/workitems?${params}`;
          requests.push(restFetch<WorkItemListResponse>(context, path));
        }

        const responses = await Promise.all(requests);
        if (cancelled) {
          return;
        }
        setItems(responses.flatMap((response) => response.data));
        setError(null);
      } catch (error: unknown) {
        if (cancelled) {
          return;
        }
        console.error("Unable to fetch the selected work items:", error);
        const message = error instanceof Error ? error.message : String(error);
        setError(`Unable to fetch the selected work items: ${message}`);
      }
    };
    const timer = setTimeout(loadItems, 150);

    return () => {
      cancelled = true;
      clearTimeout(timer);
    };
  }, [context, selectedIds]);

  const byStatus = new Map<string, number>();
  items.forEach((item) => {
    const status = item.attributes.status;
    byStatus.set(status, (byStatus.get(status) ?? 0) + 1);
  });

  return (
    <div>
      <ErrorMessage message={error} />
      <SelectionSummary selectedCount={selectedIds.length} spaceId={context?.spaceId} documentId={context?.documentId} lastEvent={lastEvent} />
      <SelectionContent selectedCount={selectedIds.length} items={items} byStatus={byStatus} />
    </div>
  );
}

Points worth noting:

Keeping up with fast selection changes

Users can change the selection several times per second (keyboard navigation, shift-click). If every change triggers a REST call, responses may arrive out of order. Two simple defenses:

// 1. Debounce: wait until the selection has been stable for 150 ms.
useEffect(() => {
  const timer = setTimeout(() => load(selectedIds), 150);
  return () => clearTimeout(timer);
}, [selectedIds]);

// 2. Ignore stale responses.
useEffect(() => {
  let cancelled = false;
  load(selectedIds).then((items) => { if (!cancelled) setItems(items); });
  return () => { cancelled = true; };
}, [selectedIds]);

Selection in Documents

In a Document, the selection is the work item the cursor is in. The event payload has the same shape, usually with one id. context.spaceId and context.documentId tell you which document; the work item itself is fetched through REST as usual.

Form extensions and navigation topics

Form extensions and navigation topics can subscribe, but they have no selection to follow: a form extension knows its work item from context.workItemId, and a navigation topic has no selection at all. Expect the event only in sidebars.

Unsubscribing

Call the returned function when the view no longer needs updates, and destroy() when the view unmounts. destroy() also unsubscribes everything that is still registered, so forgetting the individual call is not harmful, but doing both keeps the intent clear.

Development guides

Package and upload

This page covers the mechanics of getting an application onto a server: the archive layout Polarion accepts, the upload wizard, hash verification, updates and removal.

The ZIP layout

Checks performed by Polarion during upload, and the message you see when they fail:

Check Message
Exactly one top-level folder, manifest.json inside it Application's zip structure is incorrect
manifest.json is valid JSON with the required fields Application validation failed with details
Folder name equals identifier Application's zip structure is incorrect
Each view's rootDirectory/document exists Application validation failed
Each endpoint's script exists in server-scripts/ Application validation failed

The ZIP file name itself should not matter; naming it after the identifier is a convention.

Building the ZIP

The examples use a Node script (scripts/package.mjs, listed in Your first application). Equivalent shell commands:

npm run build
rm -rf package && mkdir -p package/com.example.hello
cp manifest.json package/com.example.hello/
cp -R dist package/com.example.hello/hello
cp -R server-scripts package/com.example.hello/   # if present
(cd package && zip -r ../com.example.hello.zip com.example.hello -x '*.DS_Store')

On macOS, avoid Finder's Compress on the folder: it adds __MACOSX/ entries and resource-fork files that may fail validation. Use zip as above, or the Node script.

Uploading

  1. Global Administration → Applications → Upload.
  2. Choose the ZIP and click Next. Polarion reads the manifest and computes the SHA-2 hash.
  3. Review the summary. For a new identifier it reads You are going to INSTALL the following application; for an existing one, You are going to UPDATE with New Version and Current Version columns.
  4. Click Finish. A green bar confirms the upload; the tile appears or is refreshed.

Upload step 2 for a new application

Upload step 2 for an update, comparing both versions

The change is effective immediately: static files are served and server scripts are active without a restart. Users with an open view must reload the page.

Verifying the hash

The hash shown in step 3 is the SHA-2 digest of the ZIP file (128 hexadecimal digits, the SHA-512 variant). Compute it locally to confirm you are installing the file you built:

shasum -a 512 com.example.hello.zip     # macOS / Linux
certutil -hashfile com.example.hello.zip SHA512   # Windows

The dialog refers to it as the SHA-2 hash.

Properties and delete

Select a tile to enable the Properties and Delete buttons.

Versioning

Set applicationVersion to something you can trace back to a build (1.4.0, 2026.10.05, a git describe string). Polarion displays it but appears not to compare it; an update with the same or a lower version is accepted.

Automating uploads

Uploads can be scripted against the REST API with a personal access token when com.siemens.polarion.rest.enabled and com.siemens.polarion.rest.security.restApiToken.enabled are set. The endpoint and payload are part of the REST API definition of your server (/polarion/rest/v1/definition, search for applications). Interactive upload through the UI is the supported path in the 2612 preview; treat automation as something to validate against your server version.

Building in CI

The package is reproducible from a clean checkout. A minimal GitLab CI job that keeps the ZIP and its hash as artifacts:

.gitlab-ci.yml
package:
  image: node:22
  script:
    - npm ci
    - npm run package
    - shasum -a 512 *.zip > SHA512SUMS
  artifacts:
    paths: ['*.zip', SHA512SUMS]

If the SDK is installed from your server's URL, the runner needs HTTPS access to it (or vendor the tarball as the examples do).

Removing an application cleanly

  1. Remove the applicationView elements that reference its views from form layouts and Topics configurations.
  2. Tell users who bookmarked a table with ?sidebar=polarion-application.<identifier>.<viewId> that the sidebar goes away.
  3. Global Administration → Applications: select the tile, Delete. The files are removed immediately.

Checklist before every upload

Development guides

Develop locally

Uploading a ZIP for every change is fine for integration testing but slow for UI work. Two techniques make the loop faster.

1. Mock the context in development mode

Outside Polarion, fetchContext() rejects after five seconds. Short-circuit it in development builds with a mock, so that npm run dev renders your view immediately:

src/context.ts
import { fetchContext, type PolarionContext } from 'polarion-app-sdk';

const mock: PolarionContext = {
  applicationId: 'com.example.workitemcard',
  viewId: 'card',
  projectId: 'test',
  workItemId: 'TEST-514',
  selectedWorkItemIds: ['test/TEST-514'],
  appEndpoint: 'http://localhost:5173/mock/rest',
  restBaseUrl: 'http://localhost:5173/mock/v1',
  restToken: 'dev',
};

export function getContext(): Promise<PolarionContext> {
  return import.meta.env.DEV ? Promise.resolve(mock) : fetchContext();
}

import.meta.env.DEV is true under vite and false in vite build, so the production package always uses the real SDK.

With the mock in place, REST calls go to http://localhost:5173/mock/…, which does not exist. Either mock the data layer the same way (import.meta.env.DEV ? fakeItems : restFetch(...)), or proxy to a real server as described next.

2. Proxy the REST API to a real server (untested recipe)

Vite's dev server can forward /polarion/rest/… to your Polarion server. Combined with a personal access token (PAT) that you generate in Polarion under My Account → Personal Access Tokens, the view talks to real data while you edit:

vite.config.ts
import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '');
  return {
    plugins: [react()],
    base: './',
    server: {
      proxy: {
        '/polarion/rest': {
          target: env.POLARION_URL,           // https://polarion.example.com
          changeOrigin: true,
          headers: { Authorization: `Bearer ${env.POLARION_PAT}` },
        },
      },
    },
  };
});
.env.local (not committed)
POLARION_URL=https://polarion.example.com
POLARION_PAT=…

Set the mock context's restBaseUrl to /polarion/rest/v1 (relative, so it hits the proxy) and leave restToken empty; the proxy adds the PAT. In production the real context's absolute restBaseUrl and token are used.

Keep the PAT out of source control and remove it when you are done. It carries your full Polarion permissions.

3. Testing inside Polarion still needs an upload

The view that Polarion loads is a static page under /polarion/apps/<identifier>/<rootDirectory>/. Polarion serves it from its own storage; there is no way to point an installed application at your dev server. The fastest loop for inside-Polarion testing is therefore:

npm run package     # a few seconds

followed by the upload (which is an update, no configuration changes) and a hard reload of the Polarion page. Content-hashed asset names make cache problems impossible.

4. Open the view directly

https://<host>/polarion/apps/<identifier>/views/<viewId> opens the view in a tab of its own, without the Polarion page around it. The context fetch fails there, but static-file problems (404s, wrong base, missing icons) show up immediately in the browser's network panel.

Debugging inside Polarion

A note on hot reloading and the SDK

With the Vite dev server and React Fast Refresh, components remount often. The SDK tolerates this as long as your effect cleanup calls destroy(); otherwise the second mount's events.subscribe() throws Already subscribed to event.

Development guides

Troubleshooting

Symptoms are grouped by where they show up: the administration UI, the view in the browser, and HTTP calls.

Administration

No Applications entry in Global Administration

The feature is disabled. Set the global configuration property polarionapp.enabled=true in Global Administration → Configuration Properties and reload. See Enable Applications.

Upload fails with Application's zip structure is incorrect

The ZIP does not have exactly one top-level folder named like the identifier, or manifest.json is not directly inside it. Inspect the archive:

unzip -l com.example.hello.zip

The first entries must be com.example.hello/ and com.example.hello/manifest.json. See Package and upload.

Upload fails with Application validation failed

A field in manifest.json is missing or a referenced folder/file does not exist. Compare with the manifest reference. Common causes: trailing commas in JSON, rootDirectory not matching the folder name, script not present in server-scripts/.

The Next button stays disabled

No file selected, or the selected file is not a .zip.

Views

The panel is empty or shows Loading… forever

Open the browser console and the network panel, select the iframe.

The view says it cannot reach Polarion (Timeout waiting for response to get-context)

The page is not embedded by Polarion (opened directly, or on the dev server), or the host page has not initialized the bridge. In Polarion, reload the page. If it persists in a form, check that the applicationView id matches <identifier>.<viewId> exactly.

The form layout was saved but the panel does not appear

The sidebar is missing from the Show Sidebar menu

The application's manifest has no sidebars entry, or the upload failed. Check Properties of the installed application and the manifest in the ZIP.

Already subscribed to event: selection-changed

Two subscribe() calls for the same event in one view. Subscribe once at the top level; in React make sure the effect cleanup unsubscribes and calls destroy().

HTTP calls

Polarion shows X-Rest-Token generation is not allowed on the server!

Warning dialog shown when an application view opens on a server without REST token authentication

The dialog appears as soon as an application view opens, because Polarion could not create the REST token for the view. Set com.siemens.polarion.rest.security.restApiToken.enabled=true (and com.siemens.polarion.rest.enabled=true) in polarion.properties and restart. The view still loads, but context.restToken is empty and REST calls fail.

REST call returns 401

REST call returns 403

The user is not allowed to perform the operation. Test the same action in the UI with that user. Nothing in the application can change this.

A relationship is missing from a REST response (Cannot read properties of undefined)

Sparse field sets filter relationships as well as attributes. Add the relationship name to fields[<type>], for example fields[linkedworkitems]=role,suspect,workItem, otherwise relationships.workItem is absent.

REST call returns 400

Usually a malformed query string or an unknown field in fields[…]. Read errors[].detail in the response. Use URLSearchParams to encode parameters.

Server script returns success: false

The error string is the message from your script's catch block or from the uncaught exception. Typical: objectId not passed, wrong parameter location (POST parameters must be in the JSON body), or a Java method name that does not exist (check the javadoc).

Endpoint returns HTTP 400 with Argument objectId is missing in workflow definition

Every endpoint call needs an objectId parameter (PROJECT/WI-ID). Add it to the query string (GET) or the JSON body (POST).

Endpoint returns arguments.getAsString is not a function

The script reads arguments inside a function, where the name means the function's own arguments. Capture Polarion's object at the top level: const scriptArguments = arguments;.

Endpoint returns HTTP 400 with Argument … is missing in workflow definition

The script called arguments.getAsString('x') for a parameter the view did not send. Either send it, or read optional parameters through a guarded helper (try { … } catch { return fallback; }), as the traceability example does.

Endpoint POST fails before the script runs

POST requests need Content-Type: application/json and a JSON body, even if it is {}. The body must be a flat object whose values are strings: {"objectIds": ["a","b"]} is rejected with HTTP 500 and Expected a string but was BEGIN_ARRAY; send {"objectIds": "[\"a\",\"b\"]"} and parse it in the script.

SELF_SIGNED_CERT_IN_CHAIN when installing the SDK

Node.js does not trust the server's certificate. Point NODE_EXTRA_CA_CERTS at your CA bundle, or download the tarball with a browser and install it from disk.

Where to look

Place What you find
Browser console (iframe frame) JavaScript errors, CSP violations, your own logs
Browser network panel, filter apps/ Static file 404s, endpoint responses
https://<host>/polarion/apps/<identifier>/views/<viewId> The raw view outside Polarion
Polarion server log (data/logs/main/log4j-*.log) Server script exceptions, upload validation details
Global Administration → Applications → Properties What is actually installed

Examples

Examples

Every example is a standalone project; download its source archive below. Each builds with npm install && npm run package into an upload-ready ZIP, and each page shows the full source with explanations. The first four teach the basics one step at a time; the other three show what you can build with them.

Learn the basics

Start here. Each example adds one capability to the previous one, from a page that only shows text to a view with its own server-side endpoints.

Example View type Adds Talks to
Hello Polarion Form extension The smallest possible application: a manifest, a page and the packaging nothing
Application context Form extension + sidebar + navigation topic The SDK, and what the context contains in each placement, from one build SDK
Selection sidebar Sidebar Following the selection with events; REST API queries; icons SDK events, REST API (query)
Traceability with endpoints Form extension + endpoints Your own server-side endpoints: a link tree computed on the server, and a POST that writes SDK, your own endpoints (GET, POST)

What you can build

Larger applications that combine the basics into something a team would use.

Example View type Shows Talks to
Work item card Form extension Reading a work item and its links; renaming it, changing its status, adding a comment SDK, REST API (GET, PATCH, POST)
Project dashboard Navigation topic A full page with a query box, tiles, charts by status, type and assignee, and a table SDK, REST API (list, relationships)
Release checklist Sidebar + endpoints Validation of the selection by server-side rules; bulk assignment through a writing endpoint SDK events, your own endpoints (POST, POST)

Downloads

Each example is available as an application package (upload it as it is in Global Administration → Applications) and as the source project (unzip, npm install, npm run package).

Example Identifier Version Application package Source project
Hello Polarion com.example.hello 0.2.0 com.example.hello.zip hello-polarion-source.zip
Application context com.example.context 0.2.0 com.example.context.zip application-context-source.zip
Selection sidebar com.example.selectionsidebar 0.1.1 com.example.selectionsidebar.zip selection-sidebar-source.zip
Traceability with endpoints com.example.traceability 0.2.2 com.example.traceability.zip traceability-source.zip
Work item card com.example.workitemcard 0.2.1 com.example.workitemcard.zip work-item-card-source.zip
Project dashboard com.example.dashboard 0.2.1 com.example.dashboard.zip project-dashboard-source.zip
Release checklist com.example.releasechecklist 0.2.2 com.example.releasechecklist.zip release-checklist-source.zip

The packages are the ones used for the screenshots in this guide. The source archives exclude node_modules; the SDK is installed from the vendored tarball on npm install, or replace it with your server's URL (see Install the SDK).

Common structure

All examples share the layout from Set up the project: Vite + React + TypeScript, manifest.json at the root, scripts/package.mjs for the ZIP, in the examples that call Polarion a src/polarion.ts with restFetch for REST API calls or endpointFetch for calls to the application's own endpoints, and the SDK installed from a vendored tarball in examples/_sdk/.

To use an example as the starting point of your own application:

  1. Copy the folder.
  2. Change identifier, title and publisherName in manifest.json.
  3. Replace the SDK dependency with the URL of your server: npm install https://<host>/polarion/sdk/applications/polarion-app-sdk-0.5.2-preview.tgz.
  4. npm run package, upload, place the view.

Trying them on a test server

Upload all seven; they use different identifiers and do not interfere. Then:

Examples

Hello Polarion

Hello Polarion in a work item form

Aspect Details
Folder examples/hello-polarion
Identifier com.example.hello
View form extension hello
Placement <applicationView id="p-examples-hello-polarion-com.example.hello.hello" label="Hello Polarion" height="320px"/> in a form layout
Uses nothing from Polarion: no SDK, no REST API

Source: the project is in examples/hello-polarion/ of this kit.

This is the application built step by step in Your first application. It contains only what every application needs: a manifest, a page and the packaging script. It does not use the SDK and does not talk to Polarion; the Application context example adds that.

Files

manifest.json

manifest.json
{
  "manifestVersion": "1.0",
  "identifier": "com.example.hello",
  "title": "Hello Polarion",
  "description": "The smallest possible Polarion Application: one form extension that says hello.",
  "publisherName": "Example Publisher",
  "applicationVersion": "0.2.0",
  "views": {
    "formExtensions": [
      {
        "identifier": "hello",
        "title": "Hello Polarion",
        "rootDirectory": "hello",
        "document": "index.html"
      }
    ]
  }
}

src/App.tsx

An ordinary React component. Nothing in it is specific to Polarion.

src/App.tsx
export default function App() {
  return (
    <main>
      <h1>Hello, Polarion</h1>
      <p>This panel is a Polarion Application.</p>
    </main>
  );
}

src/styles.css

src/styles.css
body {
  margin: 0;
  padding: 12px;
  font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
  font-size: 14px;
  color: #1f2933;
}

h1 {
  font-size: 1.4rem;
  margin: 0 0 8px;
}

src/main.tsx

src/main.tsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import "./styles.css";

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <App />
  </StrictMode>,
);

scripts/package.mjs

This script turns the build into the ZIP you upload to Polarion: one top-level folder named after the identifier, with manifest.json and each view's content under its rootDirectory. It stages the files under package/<identifier>/ and creates <identifier>.zip in the project root. Expand it to see how the packaging works, or read Application package for the format.

Example: scripts/package.mjs

scripts/package.mjs
// Builds the upload-ready ZIP for Polarion.
//
// Layout inside the ZIP: one top-level folder named after the application
// identifier, with manifest.json, view content under each view's
// rootDirectory (which multiple views may share), and optional server-scripts/.
// Polarion rejects a ZIP that has manifest.json directly at its root
// ("Application's zip structure is incorrect").
//
//   <identifier>/
//     manifest.json
//     <rootDirectory of each view>/   (index.html + assets)
//     server-scripts/                 (if present)
//
// Single-view projects build into dist/. Multi-view projects build one Vite
// mode per view into dist/<rootDirectory>/ (see "Set up the project" in the
// guide); this script copies whichever exists.
//
// Run with `npm run package` (which builds first).
import { cpSync, existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import AdmZip from "adm-zip";

const projectRootPath = fileURLToPath(new URL("..", import.meta.url));
const distributionPath = join(projectRootPath, "dist");

function stageViews(appStagePath, manifest) {
  const views = Object.values(manifest.views ?? {}).flat();
  if (views.length === 0) {
    throw new Error("manifest.json declares no views.");
  }

  for (const view of views) {
    const viewDist = join(distributionPath, view.rootDirectory);
    const source = existsSync(viewDist) ? viewDist : distributionPath;
    const documentPath = join(source, view.document);

    if (!existsSync(documentPath)) {
      throw new Error(`Build output for view "${view.identifier}" not found: ${documentPath}`);
    }
    cpSync(source, join(appStagePath, view.rootDirectory), { recursive: true });
  }
}

function stageServerScripts(appStagePath) {
  const serverScripts = join(projectRootPath, "server-scripts");
  if (existsSync(serverScripts)) {
    cpSync(serverScripts, join(appStagePath, "server-scripts"), { recursive: true });
  }
}

function writePackageZip(stageRoot, zipPath) {
  const zip = new AdmZip();
  zip.addLocalFolder(stageRoot);
  zip.writeZip(zipPath);
}

function packageApplication() {
  const manifest = JSON.parse(readFileSync(join(projectRootPath, "manifest.json"), "utf8"));
  const stageRootPath = join(projectRootPath, "package");
  const zipPath = join(projectRootPath, `${manifest.identifier}.zip`);

  rmSync(stageRootPath, { recursive: true, force: true });
  try {
    const appStagePath = join(stageRootPath, manifest.identifier);
    mkdirSync(appStagePath, { recursive: true });
    cpSync(join(projectRootPath, "manifest.json"), join(appStagePath, "manifest.json"));
    stageViews(appStagePath, manifest);
    stageServerScripts(appStagePath);
    writePackageZip(stageRootPath, zipPath);
  } finally {
    rmSync(stageRootPath, { recursive: true, force: true });
  }

  console.log(`Packaged ${manifest.identifier} ${manifest.applicationVersion} -> ${zipPath}`);
}

packageApplication();

Build and deploy

cd examples/hello-polarion
npm install
npm run package          # → com.example.hello.zip

Upload the ZIP in Global Administration → Applications, then add the applicationView element to a form layout as described in Form extensions.

Things to try

Examples

Application context

The Application context sidebar next to the Work Items table: the context fields of the sidebar placement

Aspect Details
Folder examples/application-context
Identifier com.example.context
Views form extension form, sidebar sidebar, navigation topic topic; one build for all three
Placement <applicationView id="p-examples-application-context-com.example.context.form" label="Application context" height="460px"/> in a form layout; <applicationView id="p-examples-application-context-com.example.context.topic"/> in Topics; the sidebar needs no configuration
Uses fetchContext(), destroy()

Source: the project is in examples/application-context/ of this kit.

Hello Polarion shows a page and nothing else. This example adds the first thing most views need: knowing where they are. It reads the context once, shows every field, and makes the rules from Application context visible:

What each placement receives

The same build runs in three places. viewId tells the code which one it is; the optional fields say what the view is attached to.

Field Form extension Sidebar, Work Items table Sidebar, Document Navigation topic
viewId form sidebar sidebar topic
projectId set set set set
workItemId the open item not set not set not set
spaceId, documentId not set not set the Document not set
selectedWorkItemIds the open item, ["drivepilot/DP-477"]; in the multi-item edit form all ticked items empty empty empty

All four columns were read on Polarion 2612; the screenshots are on this page. Ids in selectedWorkItemIds include the project, workItemId does not. In the table the sidebar was opened with three rows selected and selectedWorkItemIds stayed empty, also after Read again: a sidebar learns the selection only from selection-changed events. With three rows ticked, the form extension in the multi-item edit form below the table listed all three ids, and workItemId was the current item.

The Application context form extension in a work item: workItemId is DP-477, selectedWorkItemIds is drivepilot/DP-477

The Application context sidebar in a Document: spaceId and documentId are set

The Application context navigation topic: only projectId is set

Files

manifest.json

Three views that share one rootDirectory, app. Several views may point to the same folder, so the single dist/ build ends up in the ZIP once and serves all three placements.

manifest.json
{
  "manifestVersion": "1.0",
  "identifier": "com.example.context",
  "title": "Application context",
  "description": "One page placed as a form extension, a sidebar and a navigation topic. It shows the context Polarion hands to each placement.",
  "publisherName": "Example Publisher",
  "applicationVersion": "0.2.0",
  "views": {
    "formExtensions": [
      {
        "identifier": "form",
        "title": "Application context",
        "rootDirectory": "app",
        "document": "index.html"
      }
    ],
    "sidebars": [
      {
        "identifier": "sidebar",
        "title": "Application context",
        "rootDirectory": "app",
        "document": "index.html",
        "menuIcon": "icon16.png",
        "icon": "icon32.png"
      }
    ],
    "navigationTopics": [
      {
        "identifier": "topic",
        "title": "Application context",
        "icon": "icon30.png",
        "rootDirectory": "app",
        "document": "index.html"
      }
    ]
  }
}

src/App.tsx

src/App.tsx
import { useEffect, useState } from "react";
import { destroy, fetchContext, type PolarionContext } from "polarion-app-sdk";
import Table from "./Table";

/**
 * Describes where the view runs. The same build is placed three times; `viewId` (from manifest.json)
 * tells which placement this is, and the optional fields say what it is attached to.
 */
function placement(context: PolarionContext): string {
  switch (context.viewId) {
    case "form":
      return `the form of work item ${context.workItemId}`;
    case "sidebar":
      if (!context.documentId) {
        return "a sidebar next to the Work Items table";
      }
      const documentName = context.spaceId ? `${context.spaceId}/${context.documentId}` : `${context.documentId}`;
      return `a sidebar of Document ${documentName}`;
    case "topic":
      return `a navigation topic of project ${context.projectId}`;
    default:
      return "an unknown placement";
  }
}

export default function App() {
  const [context, setContext] = useState<PolarionContext | null>(null);
  const [readAt, setReadAt] = useState<Date | null>(null);
  const [error, setError] = useState<string | null>(null);
  // Used as a refresh trigger for re-fetching the context
  const [readCount, setReadCount] = useState(0);

  useEffect(() => {
    let cancelled = false;

    fetchContext()
      .then((context) => {
        if (cancelled) {
          return;
        }
        setContext(context);
        setReadAt(new Date());
      })
      .catch((error: unknown) => {
        if (cancelled) {
          return;
        }
        console.error("Unable to fetch the Polarion context:", error);
        const message = error instanceof Error ? error.message : String(error);
        setError(`Unable to fetch the Polarion context: ${message}`);
      });

    return () => {
      // Ignore pending results before destroy() cancels requests, including during Strict Mode cleanup.
      cancelled = true;
      destroy();
    };
  }, [readCount]);

  if (error !== null) {
    return (
      <div className="card error" role="alert">
        <strong>Could not load the Polarion context.</strong>
        <p>{error}</p>
      </div>
    );
  }

  if (context === null) {
    return <p className="muted">Waiting for the Polarion context...</p>;
  }

  return (
    <div className="card">
      <h1>Application context</h1>
      <p>
        View <strong>{context.viewId}</strong> is running in {placement(context)}.
      </p>
      <Table context={context} />
      <p className="footer">
        <button type="button" onClick={() => setReadCount((count) => count + 1)}>
          Read again
        </button>
        <span className="muted">Read at {readAt?.toLocaleTimeString() ?? "-"}. The context does not update by itself.</span>
      </p>
    </div>
  );
}

src/Table.tsx

One row per context field. Optional fields that do not apply to the placement show not set; the token shows only whether it is present.

src/Table.tsx
import type { PolarionContext } from "polarion-app-sdk";

type TableProps = {
  context: PolarionContext;
};

/** Shows an optional value, or that it is not set in this placement. */
function optional(value: string | undefined) {
  return value ? value : <span className="muted">not set</span>;
}

export default function Table({ context }: TableProps) {
  return (
    <table>
      <tbody>
        <tr>
          <th>applicationId</th>
          <td>{context.applicationId}</td>
        </tr>
        <tr>
          <th>viewId</th>
          <td>{context.viewId}</td>
        </tr>
        <tr>
          <th>projectId</th>
          <td>{optional(context.projectId)}</td>
        </tr>
        <tr>
          <th>workItemId</th>
          <td>{optional(context.workItemId)}</td>
        </tr>
        <tr>
          <th>spaceId</th>
          <td>{optional(context.spaceId)}</td>
        </tr>
        <tr>
          <th>documentId</th>
          <td>{optional(context.documentId)}</td>
        </tr>
        <tr>
          <th>selectedWorkItemIds</th>
          <td>{context.selectedWorkItemIds.length > 0 ? context.selectedWorkItemIds.join(", ") : <span className="muted">empty</span>}</td>
        </tr>
        <tr>
          <th>restBaseUrl</th>
          <td>{context.restBaseUrl}</td>
        </tr>
        <tr>
          <th>appEndpoint</th>
          <td>{context.appEndpoint}</td>
        </tr>
        <tr>
          <th>restToken</th>
          {/* The token is a credential: show that it is there, never its value. */}
          <td>{context.restToken ? "present (hidden)" : <span className="muted">not set: token authentication is off</span>}</td>
        </tr>
      </tbody>
    </table>
  );
}

Build and deploy

cd examples/application-context
npm install
npm run package          # → com.example.context.zip

Upload the ZIP in Global Administration → Applications. Then place the views:

Things to try

Examples

Selection sidebar

The Selection inspector sidebar next to the Work Items table with two rows selected

Aspect Details
Folder examples/selection-sidebar
Identifier com.example.selectionsidebar
View sidebar selection with menuIcon and icon
Placement none; choose Selection inspector in the Show Sidebar menu
Uses fetchContext(), events.subscribe(EventTypes.SELECTION_CHANGED), REST list with a Lucene id:(…) query

Source: the project is in examples/selection-sidebar/ of this kit.

What it does

  1. Fetches the context for the initial selection and subscribes to selection-changed.
  2. Whenever the list of selected ids changes, loads all of them in one REST request.
  3. Shows the count, a compact list with links, type and status chips, and a by status summary.
  4. Reports the time of the last event, which makes it easy to see the event flow while testing.

Files

manifest.json

manifest.json
{
  "manifestVersion": "1.0",
  "identifier": "com.example.selectionsidebar",
  "title": "Selection inspector",
  "description": "A sidebar that follows the work item selection in the table and shows details of the selected items.",
  "publisherName": "Example Publisher",
  "applicationVersion": "0.1.1",
  "views": {
    "sidebars": [
      {
        "identifier": "selection",
        "title": "Selection inspector",
        "rootDirectory": "selection",
        "document": "index.html",
        "menuIcon": "icon16.png",
        "icon": "icon32.png"
      }
    ]
  }
}

Icons live in public/, so Vite copies them to the root of dist/ and they end up next to index.html in the view folder, which is where the manifest paths point.

src/App.tsx

src/App.tsx
import { useEffect, useState } from "react";
import { destroy, events, EventTypes, fetchContext, type PolarionContext, type SelectionChangedData } from "polarion-app-sdk";
import { ErrorMessage, SelectionContent, SelectionSummary } from "./Components";
import { restFetch } from "./polarion";
import type { WorkItemListResponse, WorkItemResource } from "./types";

/** Selection ids may arrive as "WI-1" or "PROJECT/WI-1"; the Lucene query needs the bare id. */
function bareId(id: string): string {
  const separator = id.indexOf("/");
  return separator === -1 ? id : id.slice(separator + 1);
}

function timeNow(): string {
  return new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" });
}

export default function App() {
  const [context, setContext] = useState<PolarionContext | null>(null);
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [items, setItems] = useState<WorkItemResource[]>([]);
  const [lastEvent, setLastEvent] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  // Fetch context and subscribe to selection changes when the view mounts.
  useEffect(() => {
    let cancelled = false;

    const loadContext = async () => {
      try {
        const data = await fetchContext();
        if (cancelled) {
          return;
        }
        setContext(data);
        setSelectedIds(data.selectedWorkItemIds ?? []);
        setError(null);
      } catch (error: unknown) {
        if (cancelled) {
          return;
        }
        console.error("Unable to fetch the Polarion context:", error);
        const message = error instanceof Error ? error.message : String(error);
        setError(`Unable to fetch the Polarion context: ${message}`);
      }
    };
    loadContext();

    const unsubscribe = events.subscribe<SelectionChangedData>(EventTypes.SELECTION_CHANGED, (data) => {
      // The event contains work item IDs (<project_id>/<workitem_id>) only.
      setSelectedIds(data.selectedWorkItemIds ?? []);
      setLastEvent(timeNow());
    });

    return () => {
      // Ignore pending results before destroy() cancels requests, including during Strict Mode cleanup.
      cancelled = true;
      // Remove the subscription and release the message listener.
      unsubscribe();
      destroy();
    };
  }, []);

  // Whenever the context or selection changes, load the selected work item details.
  // The REST API returns at most 100 items per page, so request IDs in batches
  // of up to 100 and combine the results.
  // Wait 150 ms for rapid selection changes to settle and ignore outdated responses.
  useEffect(() => {
    const projectId = context?.projectId;
    if (!context || !projectId || selectedIds.length === 0) {
      setItems([]);
      return;
    }

    let cancelled = false;

    const loadItems = async () => {
      try {
        const pageSize = 100;
        const requests: Promise<WorkItemListResponse>[] = [];

        for (let i = 0; i < selectedIds.length; i += pageSize) {
          const ids = selectedIds.slice(i, i + pageSize).map(bareId);
          const params = new URLSearchParams({
            "query": `id:(${ids.join(" ")})`,
            "fields[workitems]": "id,title,status,type",
            "page[size]": String(pageSize),
          });
          const path = `/projects/${encodeURIComponent(projectId)}/workitems?${params}`;
          requests.push(restFetch<WorkItemListResponse>(context, path));
        }

        const responses = await Promise.all(requests);
        if (cancelled) {
          return;
        }
        setItems(responses.flatMap((response) => response.data));
        setError(null);
      } catch (error: unknown) {
        if (cancelled) {
          return;
        }
        console.error("Unable to fetch the selected work items:", error);
        const message = error instanceof Error ? error.message : String(error);
        setError(`Unable to fetch the selected work items: ${message}`);
      }
    };
    const timer = setTimeout(loadItems, 150);

    return () => {
      cancelled = true;
      clearTimeout(timer);
    };
  }, [context, selectedIds]);

  const byStatus = new Map<string, number>();
  items.forEach((item) => {
    const status = item.attributes.status;
    byStatus.set(status, (byStatus.get(status) ?? 0) + 1);
  });

  return (
    <div>
      <ErrorMessage message={error} />
      <SelectionSummary selectedCount={selectedIds.length} spaceId={context?.spaceId} documentId={context?.documentId} lastEvent={lastEvent} />
      <SelectionContent selectedCount={selectedIds.length} items={items} byStatus={byStatus} />
    </div>
  );
}

Points worth noting:

src/Components.tsx

Small presentational components: the error box, the summary line, the list of work items with a link to each one, and the by status summary. They receive data through props and do not talk to Polarion.

src/Components.tsx
import type { WorkItemResource } from "./types";

type ErrorMessageProps = {
  message: string | null;
};

export function ErrorMessage({ message }: ErrorMessageProps) {
  if (!message) {
    return null;
  }

  return (
    <div className="box error" role="alert">
      {message}
    </div>
  );
}

type SelectionSummaryProps = {
  selectedCount: number;
  documentId?: string;
  spaceId?: string;
  lastEvent: string | null | undefined;
};

export function SelectionSummary({ selectedCount, spaceId, documentId, lastEvent }: SelectionSummaryProps) {
  const headline = selectedCount === 0 ? "Nothing selected" : `${selectedCount} work item(s) selected`;

  return (
    <>
      <p className="headline">{headline}</p>
      {documentId && (
        <p className="muted">
          Document: {spaceId}/{documentId}
        </p>
      )}
      <p className="muted small">Last event received at {lastEvent ?? "—"}</p>
    </>
  );
}

type StatusSummaryProps = {
  byStatus: ReadonlyMap<string, number>;
};

function StatusSummary({ byStatus }: StatusSummaryProps) {
  if (byStatus.size === 0) {
    return null;
  }

  return (
    <div className="box">
      <strong>By status</strong>
      <ul className="summary">
        {[...byStatus.entries()].map(([status, count]) => (
          <li key={status}>
            {status}: {count}
          </li>
        ))}
      </ul>
    </div>
  );
}

type SelectionContentProps = {
  selectedCount: number;
  items: readonly WorkItemResource[];
  byStatus: ReadonlyMap<string, number>;
};

export function SelectionContent({ selectedCount, items, byStatus }: SelectionContentProps) {
  if (selectedCount === 0) {
    return <div className="box hint">Select one or more work items in the table.</div>;
  }

  return (
    <>
      <ul className="items">
        {items.map((item) => (
          <WorkItemRow key={item.id} item={item} />
        ))}
      </ul>
      <StatusSummary byStatus={byStatus} />
    </>
  );
}

type WorkItemRowProps = {
  item: WorkItemResource;
};

function WorkItemRow({ item }: WorkItemRowProps) {
  const separator = item.id.indexOf("/");
  const project = separator > 0 ? item.id.slice(0, separator) : undefined;
  const id = project ? item.id.slice(separator + 1) : item.id;

  return (
    <li>
      {project ? (
        <a href={`${window.location.origin}/polarion/#/project/${encodeURIComponent(project)}/workitem?id=${encodeURIComponent(id)}`} target="_top">
          {id}
        </a>
      ) : (
        <span>{id}</span>
      )}
      <span className="title">{item.attributes.title}</span>
      <span className="chip">{item.attributes.type}</span>
      <span className="chip status">{item.attributes.status}</span>
    </li>
  );
}

src/styles.css

Sidebars are narrow; the styles use a single column, small type and chips.

src/styles.css
:root {
  font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
  font-size: 13px;
  color: #1f2933;
  background: #ffffff;
}

body {
  margin: 0;
  padding: 10px;
}

.headline {
  font-size: 1.05rem;
  font-weight: 600;
  margin: 0 0 4px;
}

.box {
  border: 1px solid #d9e2ec;
  border-radius: 6px;
  padding: 10px 12px;
  margin-top: 10px;
}

.box.hint {
  background: #f5f7fa;
  color: #52606d;
}

.box.error {
  border-color: #e12d39;
  background: #fff5f5;
  color: #a61b25;
}

.items {
  list-style: none;
  padding: 0;
  margin: 8px 0 0;
}

.items li {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  align-items: center;
  padding: 6px 0;
  border-top: 1px solid #e4e7eb;
}

.items .title {
  flex: 1 1 100%;
}

.chip {
  border: 1px solid #cbd2d9;
  border-radius: 999px;
  padding: 1px 8px;
  font-size: 11px;
  background: #f5f7fa;
}

.chip.status {
  background: #e3f8ff;
  border-color: #9fd8ea;
}

.summary {
  margin: 4px 0 0;
  padding-left: 18px;
}

.muted {
  color: #7b8794;
  margin: 0 0 4px;
}

.small {
  font-size: 11px;
}

Build and deploy

cd examples/selection-sidebar
npm install
npm run package          # → com.example.selectionsidebar.zip

Upload the ZIP. Open a project's Work Items table, click Show Sidebar (top right of the table) and choose Selection inspector. Select rows with click, Shift+click and Ctrl/Cmd+click and watch the sidebar update.

Show Sidebar menu with the Selection inspector entry

Things to try

Examples

Traceability with endpoints

The Traceability panel with upstream items, the root and its downstream tree

Aspect Details
Folder examples/traceability
Identifier com.example.traceability
View form extension tree
Endpoints GET linked-tree, POST add-comment
Placement <applicationView id="p-examples-traceability-com.example.traceability.tree" label="Traceability" height="480px"/>
Uses fetchContext(), context.appEndpoint, GraalVM scripts with the tracker service

Source: the project is in examples/traceability/ of this kit.

What it does

  1. The view fetches the context and calls GET {appEndpoint}/linked-tree?objectId=test/TEST-514&depth=2, optionally with role=implements to show only links of one role.
  2. linked-tree.js runs on the server: it loads the work item, walks its direct links (downstream) recursively to the requested depth and its back links (upstream) one level, marks suspect links, and returns a nested tree in one response, together with the link roles it met.
  3. The view renders upstream items, then the root with its downstream tree: role, id, title, status, and a warning chip on suspect links.
  4. A textarea and Add comment button call POST {appEndpoint}/add-comment with { objectId, text }; add-comment.js creates the comment through the Java API and saves.

Files

manifest.json

The serverScripts.endpoints section maps paths and methods to the script files.

manifest.json
{
  "manifestVersion": "1.0",
  "identifier": "com.example.traceability",
  "title": "Traceability",
  "description": "Shows the link tree of the current work item, computed by a server script, and adds comments through a POST endpoint.",
  "publisherName": "Example Publisher",
  "applicationVersion": "0.2.2",
  "views": {
    "formExtensions": [
      {
        "identifier": "tree",
        "title": "Traceability",
        "rootDirectory": "tree",
        "document": "index.html"
      }
    ]
  },
  "serverScripts": {
    "endpoints": [
      {
        "urlPath": "linked-tree",
        "method": "GET",
        "script": "linked-tree.js"
      },
      {
        "urlPath": "add-comment",
        "method": "POST",
        "script": "add-comment.js"
      }
    ]
  }
}

server-scripts/linked-tree.js

server-scripts/linked-tree.js
// GET /polarion/apps/com.example.traceability/rest/linked-tree?objectId=PROJECT/WI-ID&depth=2[&role=implements]
//
// Runs on the Polarion server (GraalVM JavaScript) as the logged-in user.
// Walks the work item links in both directions and returns a nested tree.
// The optional `role` filter applies to links in both directions.
//
// Globals provided by Polarion:
//   context   – IScriptContext access: context.scriptContext().services().tracker()
//   arguments – IArguments: request parameters (query string for GET, JSON body for POST)

const trackerService = context.scriptContext().services().tracker();
let result = {};

// Polarion's IArguments throws ("Argument <name> is missing in workflow definition")
// when a parameter is absent. Optional parameters are therefore read through a guard.
const scriptArguments = arguments;
function getOptionalParam(name, defaultValue) {
  try {
    const value = scriptArguments.getAsString(name);
    return value === null || value === undefined || String(value) === '' ? defaultValue : String(value);
  } catch (e) {
    return defaultValue;
  }
}

function readParameters() {
  const objectId = scriptArguments.getAsString('objectId');
  if (!objectId) {
    throw new Error('objectId parameter is required (PROJECT/WI-ID)');
  }
  const depth = Math.min(3, Math.max(1, parseInt(getOptionalParam('depth', '2'), 10) || 2));
  const roleParam = getOptionalParam('role', '');
  const roleFilter = roleParam ? String(roleParam).trim().toLowerCase() : '';
  return { objectId, depth, roleFilter };
}

function findWorkItem(objectId) {
  const [projectId, workItemId] = objectId.split('/');
  const workItem = trackerService.getWorkItem(projectId, workItemId);
  if (workItem.isUnresolvable()) {
    throw new Error('Work item not found: ' + objectId);
  }
  return workItem;
}

/** Suspect flag of a link; defaults to false if the API call is unavailable. */
function isSuspect(link) {
  try {
    return link.isSuspect() === true;
  } catch (e) {
    return false;
  }
}

/** Id, name and opposite name of a link role, e.g. "verifies", "verifies", "is verified by". */
function roleInfo(link) {
  const role = link.getLinkRole();
  if (!role) return { id: '', name: '', oppositeName: '' };
  let oppositeName = '';
  try {
    oppositeName = role.getOppositeName() ? String(role.getOppositeName()) : '';
  } catch (e) {
    // Without an opposite name the filter matches the id and the name only.
  }
  return { id: String(role.getId()), name: String(role.getName()), oppositeName: oppositeName };
}

// Every role met while walking, so the view can offer them in its filter.
const rolesSeen = new Map();
function remember(info) {
  if (info.id && !rolesSeen.has(info.id)) {
    rolesSeen.set(info.id, info);
  }
}

/**
 * True when no role filter is set or the link role matches it (case-insensitive).
 * The filter compares the role id, its name and its opposite name, so "verifies" also
 * matches a back link that reads "is verified by" from this side.
 */
function roleMatches(info, roleFilter) {
  if (!roleFilter) return true;
  return [info.id, info.name, info.oppositeName].some((value) => value.toLowerCase() === roleFilter);
}

function toTreeNode(workitem) {
  return {
    id: workitem.getProjectId() + '/' + workitem.getId(),
    title: workitem.getTitle(),
    type: workitem.getType() ? workitem.getType().getName() : null,
    status: workitem.getStatus() ? workitem.getStatus().getName() : null,
  };
}

// Direct links ("this item implements X") become the downstream children.
// `ancestors` holds the items on the path from the root to here. Each branch gets its own
// copy, so a cycle stops the recursion but an item reached on two paths is expanded on both.
function buildDownstreamNodes(workitem, depth, ancestors, roleFilter) {
  const workItemId = workitem.getProjectId() + '/' + workitem.getId();
  if (depth <= 0 || ancestors.has(workItemId)) {
    return [];
  }
  const path = new Set(ancestors);
  path.add(workItemId);

  const downstream = [];
  // Java collections are easiest to iterate as arrays from GraalVM JavaScript.
  const direct = workitem.getLinkedWorkItemsStructsDirect().toArray();
  for (let i = 0; i < direct.length; i++) {
    const link = direct[i];
    const info = roleInfo(link);
    remember(info);
    if (!roleMatches(info, roleFilter)) {
      continue;
    }
    const linkedWorkItem = link.getLinkedItem();
    const node = toTreeNode(linkedWorkItem);
    node.role = info.name;
    node.suspect = isSuspect(link);
    if (depth > 1 && !path.has(node.id)) {
      node.downstream = buildDownstreamNodes(linkedWorkItem, depth - 1, path, roleFilter);
    }
    downstream.push(node);
  }
  return downstream;
}

function buildUpstreamNodes(workItem, roleFilter) {
  const upstream = [];
  const back = workItem.getLinkedWorkItemsStructsBack().toArray();
  for (let i = 0; i < back.length; i++) {
    const link = back[i];
    const info = roleInfo(link);
    remember(info);
    // The role filter applies in both directions: a requirement filtered by "verifies"
    // shows the test cases that verify it, which are back links seen from here.
    if (!roleMatches(info, roleFilter)) {
      continue;
    }
    const node = toTreeNode(link.getLinkedItem());
    // Seen from this item a back link reads in the opposite direction ("is verified by").
    node.role = info.oppositeName || info.name;
    node.suspect = isSuspect(link);
    upstream.push(node);
  }
  return upstream;
}

try {
  const { objectId, depth, roleFilter } = readParameters();
  const workItem = findWorkItem(objectId);

  const rootWorkItemNode = toTreeNode(workItem);
  rootWorkItemNode.downstream = buildDownstreamNodes(workItem, depth, new Set(), roleFilter);
  rootWorkItemNode.upstream = buildUpstreamNodes(workItem, roleFilter);

  result = { item: rootWorkItemNode, roles: Array.from(rolesSeen.values()) };
} catch (e) {
  // An `error` key turns the response into an error response for the caller.
  result = { error: 'linked-tree failed: ' + e };
}

result;

server-scripts/add-comment.js

server-scripts/add-comment.js
// POST /polarion/apps/com.example.traceability/rest/add-comment
// Body: { "objectId": "PROJECT/WI-ID", "text": "…" }
//
// Adds a plain-text comment to the work item. Runs as the logged-in user, who
// therefore needs permission to comment on the item.

const trackerService = context.scriptContext().services().tracker();
const Text = Java.type('com.polarion.core.util.types.Text');
let result = {};

try {
  const fullId = arguments.getAsString('objectId');
  const text = arguments.getAsString('text');
  if (!fullId) {
    throw new Error('objectId parameter is required (PROJECT/WI-ID)');
  }
  if (!text || text.trim() === '') {
    throw new Error('text parameter is required');
  }

  const [projectId, workitemId] = fullId.split('/');
  const workitem = trackerService.getWorkItem(projectId, workitemId);
  if (workitem.isUnresolvable()) {
    throw new Error('Work item not found: ' + fullId);
  }

  // createComment(IText text, String title, IComment parent) returns the new
  // IComment. Saving the work item alone does not persist it; save the comment.
  const comment = workitem.createComment(Text.plain(text), 'Traceability app', null);
  comment.save();

  // The id may not be assigned yet right after save; report it when available.
  const commentId = comment.getId();
  result = { ok: true, commentId: commentId ? String(commentId) : null };
} catch (e) {
  result = { error: 'add-comment failed: ' + e };
}

result;

Note

Text.plain() comes from com.polarion.core.util.types.Text; createComment(IText, String, IComment) is the IWorkItem method and returns the new IComment, which must be saved with comment.save(). Saving the work item alone does not persist the comment.

src/polarion.ts

The endpoint helper: same token header as for REST, plus unwrapping of the { success, data, error } envelope.

src/polarion.ts
import type { PolarionContext } from "polarion-app-sdk";

/** Envelope that Polarion wraps around every server-script response. */
interface Envelope<T> {
  timestamp?: string;
  success?: boolean;
  error?: string;
  data?: T;
}

/**
 * Calls one of the application's own endpoints declared in
 * manifest.json under `serverScripts.endpoints`.
 *
 * `context.appEndpoint` is the absolute base URL of those endpoints, for example
 * `https://host/polarion/apps/com.example.traceability/rest` (no trailing slash), so `path`
 * starts with a slash, as in `restFetch`: `"/validate"`. The same
 * `X-Polarion-REST-Token` header as for the REST API authenticates the call.
 * The response envelope is unwrapped so callers only see the script's result.
 */
export async function endpointFetch<T>(context: PolarionContext, path: string, init: RequestInit = {}): Promise<T> {
  const headers = new Headers(init.headers);
  headers.set("X-Polarion-REST-Token", context.restToken ?? "");
  headers.set("Accept", "application/json");
  if (init.body !== undefined && !headers.has("Content-Type")) {
    headers.set("Content-Type", "application/json");
  }

  const response = await fetch(`${context.appEndpoint}${path}`, { ...init, headers });

  // Script errors come back as HTTP 400 with the envelope, so parse the body
  // whenever it is JSON and surface the script's own message.
  const text = await response.text();
  let envelope: Envelope<T> | undefined;
  try {
    envelope = JSON.parse(text) as Envelope<T>;
  } catch {
    envelope = undefined;
  }
  if (envelope && (envelope.success === false || envelope.error)) {
    throw new Error(envelope.error ?? "Server script reported an error.");
  }
  if (!response.ok || !envelope) {
    throw new Error(`Endpoint ${response.status}: ${text}`);
  }
  return envelope.data as T;
}

src/App.tsx

src/App.tsx
import { useEffect, useRef, useState } from "react";
import { destroy, fetchContext, type PolarionContext } from "polarion-app-sdk";
import { endpointFetch } from "./polarion";
import LinkTree from "./LinkTree";
import type { AddCommentResult, LinkedTreeResult, LinkRole, TreeNode, CommentState } from "./types";

export default function App() {
  const [tree, setTree] = useState<TreeNode | null>(null);
  const [role, setRole] = useState("");
  const [roles, setRoles] = useState<LinkRole[]>([]);
  const [comment, setComment] = useState("");
  const [commentState, setCommentState] = useState<CommentState>({ kind: "idle" });
  const [error, setError] = useState<string | null>(null);

  // Keep the fetched context available to filter changes without triggering a render.
  const contextRef = useRef<PolarionContext | null>(null);
  // Changing the role quickly starts several loads; only the latest request may update the view.
  const requestRef = useRef(0);

  // Loads the linked workitem tree rooted at the selected work item. The server follows downstream
  // links recursively to the requested depth and includes direct upstream links; the role filter
  // applies to links in both directions.
  const loadTree = async (context: PolarionContext, roleFilter = "") => {
    const request = ++requestRef.current;
    setError(null);

    // Build the query from the current work item and optional role filter selected.
    const params = new URLSearchParams({
      objectId: `${context.projectId}/${context.workItemId}`,
      depth: "2",
    });
    if (roleFilter.trim() !== "") {
      params.set("role", roleFilter.trim());
    }

    try {
      // Fetch the linked tree from the server using the constructed query parameters.
      const result = await endpointFetch<LinkedTreeResult>(context, `/linked-tree?${params}`);
      // Ignore responses that finished after a more recent load was started.
      if (request !== requestRef.current) {
        return;
      }

      setTree(result.item);
      // Keep roles from previous responses so filtering does not hide other available options.
      setRoles((knownRoles) => {
        const byId = new Map(knownRoles.map((knownRole) => [knownRole.id, knownRole]));
        const resultRoles = result.roles ?? [];
        resultRoles.forEach((resultRole) => byId.set(resultRole.id, resultRole));
        return [...byId.values()].sort((a, b) => a.name.localeCompare(b.name));
      });
    } catch (cause) {
      // Only show errors from the latest request; an outdated failure is no longer relevant.
      if (request === requestRef.current) {
        console.error("Unable to load the linked work items:", cause);
        const message = cause instanceof Error ? cause.message : String(cause);
        setError(`Unable to load the linked work items: ${message}`);
      }
    }
  };

  const addCommentHandler = async () => {
    const context = contextRef.current;
    if (!context) {
      setCommentState({ kind: "error", message: "Work item context is not available." });
      return;
    }

    setCommentState({ kind: "saving" });
    try {
      const result = await endpointFetch<AddCommentResult>(context, "/add-comment", {
        method: "POST",
        body: JSON.stringify({
          objectId: `${context.projectId}/${context.workItemId}`,
          text: comment.trim(),
        }),
      });
      if (!result.ok) {
        throw new Error("The server did not confirm that the comment was added.");
      }

      setComment("");
      setCommentState({
        kind: "success",
        message: `Comment added${result.commentId ? ` (${result.commentId})` : ""}. Reload the page to see it.`,
      });
    } catch (cause: unknown) {
      console.error("Unable to add the comment:", cause);
      const message = cause instanceof Error ? cause.message : String(cause);
      setCommentState({ kind: "error", message: `Unable to add the comment: ${message}` });
    }
  };

  // Initialize the view by fetching the context and loading the tree.
  useEffect(() => {
    let cancelled = false;

    const initialize = async () => {
      try {
        const context: PolarionContext = await fetchContext();
        if (cancelled) {
          return;
        }
        if (!context.projectId || !context.workItemId) {
          setError("This view must be placed on a work item form.");
          return;
        }

        contextRef.current = context;
        await loadTree(context);
      } catch (cause) {
        if (!cancelled) {
          console.error("Unable to fetch the Polarion context:", cause);
          const message = cause instanceof Error ? cause.message : String(cause);
          setError(`Unable to fetch the Polarion context: ${message}`);
        }
      }
    };

    initialize();

    return () => {
      // Ignore pending results before destroy() cancels requests, including during Strict Mode cleanup.
      cancelled = true;
      requestRef.current += 1;
      destroy();
    };
  }, []);

  const applyRole = (selectedRole: string) => {
    setRole(selectedRole);
    if (contextRef.current) {
      void loadTree(contextRef.current, selectedRole);
    }
  };

  if (error) {
    return <div className="card error">{error}</div>;
  } else if (!tree) {
    return <p className="muted">Computing the link tree on the server…</p>;
  }

  return (
    <div className="card">
      <LinkTree tree={tree} roles={roles} role={role} onRoleChange={applyRole} />

      <h2>Add a comment</h2>
      <textarea rows={3} value={comment} onChange={(event) => setComment(event.target.value)} placeholder="Comment text" />
      <div className="row">
        <button onClick={addCommentHandler} disabled={commentState.kind === "saving" || comment.trim() === ""}>
          {commentState.kind === "saving" ? "Saving…" : "Add comment"}
        </button>
        {commentState.message && <span className={commentState.kind === "success" ? "ok" : "err"}>{commentState.message}</span>}
      </div>
    </div>
  );
}

Points worth noting:

src/LinkTree.tsx

The role dropdown and the tree. LinkTree receives the tree and the known roles as props and reports a new role through onRoleChange; App.tsx then reloads the tree from the endpoint. A private Node component renders one node and calls itself for the node's downstream children.

src/LinkTree.tsx
import type { LinkRole, TreeNode } from "./types";

type LinkTreeProps = {
  tree: TreeNode;
  roles: LinkRole[];
  role: string;
  onRoleChange: (role: string) => void;
};

function itemUrl(fullId: string): string {
  const [project, id] = fullId.split("/");
  return `${window.location.origin}/polarion/#/project/${project}/workitem?id=${id}`;
}

function Node({ node, level = 0, isRoot = false }: { node: TreeNode; level?: number; isRoot?: boolean }) {
  const workitemId = node.id.split("/")[1] ?? node.id;

  const className = isRoot ? "node root" : "node";
  const style = { paddingLeft: `${level * 20}px` };
  return (
    <>
      <div className={className} style={style}>
        {node.role && <span className="role">{node.role}</span>}
        <a href={itemUrl(node.id)} target="_top">
          {workitemId}
        </a>
        <span className="title">{node.title}</span>
        {node.type && <span className="chip">{node.type}</span>}
        {node.status && <span className="chip status">{node.status}</span>}
        {node.suspect && (
          <span className="chip warn" title="The linked item changed after the link was created">
            suspect
          </span>
        )}
      </div>
      {node.downstream?.map((child) => (
        <Node key={child.id} node={child} level={level + 1} />
      ))}
    </>
  );
}

export default function LinkTree({ tree, roles, role, onRoleChange }: LinkTreeProps) {
  return (
    <>
      {/* Optional role filter, passed to the GET endpoint as the `role` parameter. It offers the
          roles found on this item's links and applies to upstream and downstream links alike. */}
      <div className="row filter">
        <label htmlFor="role">Link role</label>
        <select id="role" value={role} onChange={(event) => onRoleChange(event.target.value)}>
          <option value="">All roles</option>
          {roles.map((linkRole) => (
            <option key={linkRole.id} value={linkRole.id}>
              {linkRole.oppositeName && linkRole.oppositeName !== linkRole.name ? `${linkRole.name} / ${linkRole.oppositeName}` : linkRole.name}
            </option>
          ))}
        </select>
      </div>

      <h2>Upstream (items linking to this one)</h2>
      {tree.upstream?.length ? tree.upstream.map((parent) => <Node key={parent.id} node={parent} />) : <p className="muted">No upstream links.</p>}

      <h2>This item and its downstream links</h2>
      <Node node={tree} isRoot />
      {!tree.downstream?.length && <p className="muted">No downstream links.</p>}
    </>
  );
}

Build and deploy

cd examples/traceability
npm install
npm run package          # → com.example.traceability.zip (with server-scripts/)

Upload the ZIP, add the applicationView element to a form layout, and open a work item that has links. To see upstream links, open an item that is the target of a link from another item.

Things to try

Examples

Work item card

The Work item card panel showing title, badges, description, links and the edit forms

Aspect Details
Folder examples/work-item-card
Identifier com.example.workitemcard
View form extension card
Placement <applicationView id="p-examples-work-item-card-com.example.workitemcard.card" label="Work item card" height="640px"/>
Uses fetchContext(), REST GET …/workitems/{id}, GET …/linkedworkitems?include=workItem, PATCH …/workitems/{id} (title), GET …/actions/getWorkflowActions and PATCH …?workflowAction= (status), POST …/workitems/{id}/comments

Source: the project is in examples/work-item-card/ of this kit.

What it does

  1. Fetches the context to learn projectId, workItemId, restBaseUrl and restToken.
  2. Loads the work item with a sparse field set, then its linked work items with include=workItem so that the titles arrive in the same response. Suspect links get a warning badge.
  3. Renders a card: title, badges for type, status, priority and severity with their Polarion names and icons, the HTML description, and the links with roles.
  4. Offers three write operations, each a small component: Rename (PATCH attributes.title), Status (runs a workflow action, so the workflow's conditions and required fields apply) and Add comment (POST …/comments).

Files

manifest.json

manifest.json
{
  "manifestVersion": "1.0",
  "identifier": "com.example.workitemcard",
  "title": "Work item card",
  "description": "Shows the current work item, its linked work items and lets the user rename it through the Polarion REST API.",
  "publisherName": "Example Publisher",
  "applicationVersion": "0.2.1",
  "views": {
    "formExtensions": [
      {
        "identifier": "card",
        "title": "Work item card",
        "rootDirectory": "card",
        "document": "index.html"
      }
    ]
  }
}

src/polarion.ts

The REST helper used by all REST examples. It is the only place that knows about the token header.

src/polarion.ts
import type { PolarionContext } from "polarion-app-sdk";

/**
 * Calls the Polarion REST API (JSON:API) on behalf of the logged-in user.
 *
 * `context.restBaseUrl` is the absolute base URL of the REST API, for example
 * `https://host/polarion/rest/v1` (no trailing slash). `context.restToken` is a
 * short-lived token that Polarion hands to the application view; it must be
 * sent in the `X-Polarion-REST-Token` header.
 */
export async function restFetch<T>(context: PolarionContext, path: string, init: RequestInit = {}): Promise<T> {
  const headers = new Headers(init.headers);
  headers.set("X-Polarion-REST-Token", context.restToken ?? "");
  headers.set("Accept", "application/json");
  if (init.body !== undefined && !headers.has("Content-Type")) {
    headers.set("Content-Type", "application/json");
  }

  const response = await fetch(`${context.restBaseUrl}${path}`, { ...init, headers });
  if (!response.ok) {
    throw new Error(`REST ${response.status}: ${await response.text()}`);
  }
  if (response.status === 204) {
    return null as T;
  }
  return (await response.json()) as T;
}

src/types.ts

Only the parts of the JSON:API documents the component reads. Typing the full REST schema is unnecessary; keep the types close to what you use.

src/types.ts
/** Minimal JSON:API shapes used by this example. */

export interface WorkItemAttributes {
  title: string;
  status: string;
  type: string;
  priority?: string;
  severity?: string;
  description?: { type: string; value: string };
}

export interface WorkItemResource {
  /** "PROJECT/WI-ID" */
  id: string;
  type: "workitems";
  attributes: WorkItemAttributes;
}

export interface WorkItemResponse {
  data: WorkItemResource;
}

export interface LinkedWorkItemResource {
  id: string;
  type: "linkedworkitems";
  attributes: { role: string; suspect?: boolean };
  relationships: { workItem: { data: { id: string; type: "workitems" } } };
}

export interface LinkedWorkItemsResponse {
  data: LinkedWorkItemResource[];
  included?: WorkItemResource[];
}

/** A linked work item flattened for rendering. */
export interface LinkedItem {
  role: string;
  suspect: boolean;
  id: string;
  title: string;
  status: string;
}

/** One entry of GET …/workitems/{id}/actions/getWorkflowActions. */
export interface WorkflowAction {
  /** Position in the list; the PATCH does not accept it. */
  id: string;
  /** Action id from the workflow configuration, e.g. "start_progress": the value for `?workflowAction=`. */
  nativeActionId: string;
  name: string;
  targetStatus: string;
  available: boolean;
  unavailableReason?: string;
  requiredFields?: string[];
}

export interface WorkflowActionsResponse {
  data?: WorkflowAction[];
}

/** UI state of a save action. */
export type ActionState = { kind: "idle" | "saving" | "ok" | "error"; text?: string };

src/App.tsx

src/App.tsx
import { useCallback, useEffect, useState } from "react";
import { destroy, fetchContext, type PolarionContext } from "polarion-app-sdk";
import DOMPurify from "dompurify";
import { restFetch } from "./polarion";
import type { LinkedItem, LinkedWorkItemsResponse, WorkItemAttributes, WorkItemResponse } from "./types";
import { loadCurrentOption, loadOptionsForType, type EnumOption } from "./fields";
import RenameForm from "./components/RenameForm";
import StatusForm from "./components/StatusForm";
import CommentForm from "./components/CommentForm";

interface Badge {
  field: string;
  /** Shown before the option name where the name alone is ambiguous ("Medium"). */
  label?: string;
  option: EnumOption;
}

interface Card {
  id: string;
  attributes: WorkItemAttributes;
  badges: Badge[];
  linked: LinkedItem[];
}

/** An enumeration value with Polarion's icon and name, colored like in Polarion. */
function OptionBadge({ badge }: { badge: Badge }) {
  const { option } = badge;
  return (
    <span className={`badge ${badge.field}`} style={option.color ? { borderColor: option.color } : undefined} title={`${badge.field}: ${option.id}`}>
      {option.iconURL && <img src={`${window.location.origin}${option.iconURL}`} alt="" />}
      {badge.label && <span className="badge-label">{badge.label}</span>}
      {option.name}
    </span>
  );
}

// Enumeration fields shown as badges, with the label for those whose value alone is unclear.
const BADGE_FIELDS: { field: keyof WorkItemAttributes; label?: string }[] = [{ field: "type" }, { field: "status" }, { field: "priority", label: "Priority" }, { field: "severity", label: "Severity" }];

/**
 * Loads the work item and its links, plus the display names and icons of its enumeration
 * values. The REST API returns enumeration fields as ids ("workpackage", "55.0"); the names
 * come from getCurrentOptions, and for linked items from the status options of their type.
 */
async function loadCard(context: PolarionContext): Promise<Card> {
  const { projectId, workItemId } = context;
  if (!projectId || !workItemId) {
    throw new Error("This view must be placed on a work item form (projectId / workItemId missing).");
  }
  const base = `/projects/${projectId}/workitems/${workItemId}`;

  const item = await restFetch<WorkItemResponse>(context, `${base}?fields[workitems]=id,title,status,type,priority,severity,description`);

  const links = await restFetch<LinkedWorkItemsResponse>(context, `${base}/linkedworkitems?fields[linkedworkitems]=role,suspect,workItem&include=workItem&fields[workitems]=id,title,status,type`);

  // The linked items only carry an id; the full work items travel in `included`.
  const byId = new Map((links.included ?? []).map((wi) => [wi.id, wi]));

  // Display values: one call per badge field, one per work item type among the links.
  const present = BADGE_FIELDS.filter((b) => item.data.attributes[b.field]);
  const linkedTypes = [...new Set((links.included ?? []).map((wi) => wi.attributes.type))];
  const [options, statusByType] = await Promise.all([Promise.all(present.map((b) => loadCurrentOption(context, b.field).catch(() => null))), Promise.all(linkedTypes.map((t) => loadOptionsForType(context, "status", t).catch(() => new Map<string, EnumOption>()))).then((maps) => new Map(linkedTypes.map((t, i) => [t, maps[i]])))]);
  const badges = present.flatMap((b, i) => {
    const option = options[i] ?? { id: String(item.data.attributes[b.field]), name: String(item.data.attributes[b.field]) };
    return [{ field: b.field, label: b.label, option }];
  });

  const linked: LinkedItem[] = links.data.map((link) => {
    const target = byId.get(link.relationships.workItem.data.id);
    const status = target?.attributes.status ?? "";
    return {
      role: link.attributes.role,
      suspect: link.attributes.suspect === true,
      id: link.relationships.workItem.data.id,
      title: target?.attributes.title ?? "",
      status: (target && statusByType.get(target.attributes.type)?.get(status)?.name) ?? status,
    };
  });

  return { id: item.data.id, attributes: item.data.attributes, badges, linked };
}

export default function App() {
  const [context, setContext] = useState<PolarionContext | null>(null);
  const [card, setCard] = useState<Card | null>(null);
  const [error, setError] = useState<string | null>(null);

  const reload = useCallback(async (ctx: PolarionContext) => {
    try {
      setCard(await loadCard(ctx));
      setError(null);
    } catch (error) {
      console.error("Unable to load the work item:", error);
      const message = error instanceof Error ? error.message : String(error);
      setError(`Unable to load the work item: ${message}`);
    }
  }, []);

  useEffect(() => {
    let cancelled = false;

    fetchContext()
      .then((ctx) => {
        if (cancelled) {
          return;
        }
        setContext(ctx);
        return reload(ctx);
      })
      .catch((error: unknown) => {
        if (cancelled) {
          return;
        }
        console.error("Unable to fetch the Polarion context:", error);
        const message = error instanceof Error ? error.message : String(error);
        setError(`Unable to fetch the Polarion context: ${message}`);
      });

    return () => {
      // Ignore pending results before destroy() cancels requests, including during Strict Mode cleanup.
      cancelled = true;
      destroy();
    };
  }, [reload]);

  if (error) {
    return <div className="card error">{error}</div>;
  }
  if (!context || !card) {
    return <p className="muted">Loading work item…</p>;
  }

  const a = card.attributes;
  const origin = window.location.origin;

  return (
    <div className="card">
      <h1>{a.title}</h1>
      <div className="badges">
        {card.badges.map((b) => (
          <OptionBadge key={b.field} badge={b} />
        ))}
      </div>

      <h2>Description</h2>
      {a.description?.value ? (
        // The description is HTML written by users. Sanitize it before it enters the DOM:
        // the view runs on Polarion's origin with the user's session.
        <div className="description" dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(a.description.value) }} />
      ) : (
        <p className="muted">No description.</p>
      )}

      <h2>Linked work items</h2>
      {card.linked.length === 0 ? (
        <p className="muted">No links.</p>
      ) : (
        <ul className="links">
          {card.linked.map((link) => {
            const [project, id] = link.id.split("/");
            return (
              <li key={`${link.role}-${link.id}`}>
                <span className="role">{link.role}</span>
                <a href={`${origin}/polarion/#/project/${project}/workitem?id=${id}`} target="_top">
                  {id}
                </a>{" "}
                {link.title} <span className="muted">({link.status})</span>
                {link.suspect && <span className="badge warn">suspect</span>}
              </li>
            );
          })}
        </ul>
      )}

      {/* Three ways of writing through the REST API, each in its own small component. */}
      <RenameForm context={context} resourceId={card.id} currentTitle={a.title} onSaved={() => reload(context)} />
      <StatusForm context={context} resourceId={card.id} currentStatus={a.status} workItemType={a.type} onSaved={() => reload(context)} />
      <CommentForm context={context} />
    </div>
  );
}

Points worth noting:

Writing: status and comments

src/components/StatusForm.tsx
import { useEffect, useState } from "react";
import type { PolarionContext } from "polarion-app-sdk";
import { restFetch } from "../polarion";
import RequiredFields from "./RequiredFields";
import { inputFor, isEmpty, loadFieldsMetadata, loadOptionsForType, toJsonApi, type EnumOption, type FieldMeta } from "../fields";
import type { ActionState, WorkflowAction, WorkflowActionsResponse } from "../types";

interface CurrentValuesResponse {
  data: {
    attributes?: Record<string, unknown>;
    relationships?: Record<string, { data?: unknown }>;
  };
}

interface Props {
  context: PolarionContext;
  resourceId: string;
  currentStatus: string;
  /** Work item type id; status names depend on it. */
  workItemType: string;
  onSaved: () => Promise<void>;
}

/**
 * Changes the status by running a workflow action, as the status menu in Polarion does.
 *
 * Writing `attributes.status` directly would bypass the workflow: conditions, required
 * fields and functions of the transition would not run. Instead the component lists the
 * actions the workflow offers for the current status and runs the chosen one with
 * `PATCH …/workitems/{id}?workflowAction=<nativeActionId>`.
 *
 * When the action requires fields that are still empty, the form asks for them and sends
 * them in the same PATCH, as the transition dialog in Polarion does.
 */
export default function StatusForm({ context, resourceId, currentStatus, workItemType, onSaved }: Props) {
  const [actions, setActions] = useState<WorkflowAction[] | null>(null);
  const [actionId, setActionId] = useState("");
  const [state, setState] = useState<ActionState>({ kind: "idle" });
  // Field types of this work item (built-in and custom), loaded once.
  const [metadata, setMetadata] = useState<Record<string, FieldMeta> | null>(null);
  // Required fields of the chosen action that are empty on the work item, and their new values.
  const [missing, setMissing] = useState<FieldMeta[] | null>(null);
  const [values, setValues] = useState<Record<string, string>>({});

  const path = `/projects/${context.projectId}/workitems/${context.workItemId}`;

  useEffect(() => {
    loadFieldsMetadata(context)
      .then(setMetadata)
      .catch(() => setMetadata({}));
  }, [context]);

  // Display names of the statuses, so actions read "Review → Reviewed" instead of "→ reviewed".
  const [statuses, setStatuses] = useState<Map<string, EnumOption>>(new Map());
  useEffect(() => {
    loadOptionsForType(context, "status", workItemType)
      .then(setStatuses)
      .catch(() => setStatuses(new Map()));
  }, [context, workItemType]);
  const statusName = (id: string) => statuses.get(id)?.name ?? id;

  // The workflow decides which actions exist for the current status and whether the
  // user may run them; unavailable ones carry the reason.
  useEffect(() => {
    let cancelled = false;
    // Drop the previous status's actions at once, so a stale transition cannot be chosen
    // while the new list loads.
    setActions(null);
    setActionId("");
    restFetch<WorkflowActionsResponse>(context, `${path}/actions/getWorkflowActions`)
      .then((r) => {
        if (!cancelled) setActions(r.data ?? []);
      })
      .catch((e: unknown) => {
        if (!cancelled) setState({ kind: "error", text: e instanceof Error ? e.message : String(e) });
      });
    return () => {
      cancelled = true;
    };
  }, [context, path, currentStatus]);

  const selected = actions?.find((a) => a.nativeActionId === actionId);

  // Read the current values of the action's required fields; only empty ones need input.
  // Each field's metadata says whether it is an attribute or a relationship and how to edit it.
  useEffect(() => {
    setValues({});
    const required = selected?.requiredFields ?? [];
    if (required.length === 0) {
      setMissing([]);
      return;
    }
    setMissing(null);
    if (!metadata) return;
    const metas = required.map((id): FieldMeta => metadata[id] ?? { id, label: id, part: "attributes", type: { kind: "unknown" } });
    let cancelled = false;
    restFetch<CurrentValuesResponse>(context, `${path}?fields[workitems]=${required.join(",")}`)
      .then((r) => {
        const empty = metas.filter((m) => (m.part === "attributes" ? isEmpty(r.data.attributes?.[m.id]) : isEmpty(r.data.relationships?.[m.id]?.data)));
        if (cancelled) return;
        setMissing(empty);
        // A checkbox has a value even when it is not ticked.
        setValues(Object.fromEntries(empty.filter((m) => inputFor(m) === "checkbox").map((m) => [m.id, "false"])));
      })
      .catch(() => {
        if (!cancelled) setMissing(metas);
      });
    return () => {
      cancelled = true;
    };
  }, [context, path, selected, metadata]);

  // Run is possible once every empty required field is editable here and has a value.
  const complete = missing !== null && missing.every((m) => inputFor(m) !== null && (values[m.id] ?? "").trim() !== "");

  async function run() {
    if (!selected) return;
    setState({ kind: "saving" });
    try {
      // The action runs on the server with the workflow's conditions and functions. The
      // parameter takes the action id from the workflow configuration (nativeActionId).
      // The body carries the required fields, which Polarion sets before the transition;
      // the action itself sets the target status. The metadata decides where each value
      // goes and in which shape (string, rich text, enumeration list, relationship, …).
      const attributes: Record<string, unknown> = {};
      const relationships: Record<string, unknown> = {};
      for (const field of missing ?? []) {
        (field.part === "attributes" ? attributes : relationships)[field.id] = toJsonApi(field, values[field.id].trim());
      }
      await restFetch(context, `${path}?workflowAction=${encodeURIComponent(selected.nativeActionId)}`, {
        method: "PATCH",
        body: JSON.stringify({ data: { type: "workitems", id: resourceId, attributes, relationships } }),
      });
      await onSaved();
      // The new status offers different actions; they reload through the effect above.
      setState({ kind: "ok", text: `${selected.name}: status is now ${statusName(selected.targetStatus)}.` });
    } catch (e) {
      // A condition or a required field that blocks the transition comes back as an HTTP error.
      setState({ kind: "error", text: e instanceof Error ? e.message : String(e) });
    }
  }

  return (
    <>
      <h2>Status</h2>
      {actions === null && state.kind !== "error" && <p className="muted">Loading workflow actions…</p>}
      {actions !== null && actions.length === 0 && <p className="muted">The workflow offers no action from status {statusName(currentStatus)}.</p>}
      {actions !== null && actions.length > 0 && (
        <div className="row">
          <select value={actionId} onChange={(e) => setActionId(e.target.value)}>
            <option value="">Choose an action…</option>
            {actions.map((a) => (
              <option key={a.nativeActionId} value={a.nativeActionId} disabled={!a.available}>
                {a.name} → {statusName(a.targetStatus)}
                {a.available ? "" : ` (${a.unavailableReason ?? "not available"})`}
              </option>
            ))}
          </select>
          <button onClick={run} disabled={!selected || !selected.available || !complete || state.kind === "saving"}>
            {state.kind === "saving" ? "Saving…" : "Run action"}
          </button>
        </div>
      )}
      {selected && missing && missing.length > 0 && (
        <>
          <p className="muted">{selected.name} requires these fields:</p>
          <RequiredFields context={context} fields={missing} values={values} onChange={(field, value) => setValues((v) => ({ ...v, [field]: value }))} />
        </>
      )}
      {state.kind === "ok" && <p className="ok">{state.text}</p>}
      {state.kind === "error" && <p className="err">{state.text}</p>}
    </>
  );
}

Change the status through a workflow action, never by writing attributes.status. A PATCH that sets status directly is accepted, but it bypasses the workflow: the transition's conditions, required fields and functions do not run, and the work item can end up in a state the workflow cannot leave cleanly.

The component does what the status menu in Polarion does:

  1. GET …/workitems/{id}/actions/getWorkflowActions returns the actions offered from the current status. Each one carries name, targetStatus, available with an unavailableReason, and requiredFields. Unavailable actions are shown disabled with the reason.
  2. PATCH …/workitems/{id}?workflowAction=<nativeActionId> runs the chosen action. Pass nativeActionId, the action id from the workflow configuration (for example reviewed); the numeric id of the list entry is rejected with The workflow action '8' was not found.
  3. Required fields are filled in the same request, as the transition dialog in Polarion does. When an action lists requiredFields, the component reads their current values and asks only for the empty ones. It sends them in attributes (or, for assignee, in relationships) of the PATCH that carries ?workflowAction=. Polarion sets the fields first and then runs the transition. Verified on 2612: Reject with resolution: "invalid" in the body moves a work package to rejected in one call.
  4. The workflow checks still apply. Without the resolution, Reject comes back as HTTP 400: The required field 'Resolution' (id: 'resolution') of Work Item … is empty. The component shows that message.
  5. Fields that the action clears (clearedFields) are emptied after the transition. A value sent for such a field in the same request does not survive.

Nothing in the form is specific to a field. The required fields differ per transition, and the inputs adapt to whatever the workflow and the work item type define, custom fields included:

Verified on 2612 with a work package: Quickly Accept asked for Initial Estimate (a duration, text input), Reject for Resolution (an enumeration, select). Both moved the work item in one request. Field kinds the example does not edit, such as structures, show a note pointing to the work item form, and Run action stays disabled.

src/fields.ts
import type { PolarionContext } from "polarion-app-sdk";
import { restFetch } from "./polarion";

/**
 * Field types as returned by GET …/workitems/{id}/actions/getFieldsMetadata.
 * The same call describes built-in and custom fields of this work item's type.
 */
export interface FieldType {
  kind: string; // "string", "text", "enumeration", "date", "date-time", "duration", "boolean", "relationship", …
  enumName?: string;
  targetResourceTypes?: string[];
  multi?: boolean;
}

export interface FieldMeta {
  id: string;
  label: string;
  /** Attributes and relationships travel in different parts of a JSON:API body. */
  part: "attributes" | "relationships";
  type: FieldType;
}

interface MetadataResponse {
  data: {
    attributes?: Record<string, { label?: string; type: FieldType }>;
    relationships?: Record<string, { label?: string; type: FieldType }>;
  };
}

export async function loadFieldsMetadata(context: PolarionContext): Promise<Record<string, FieldMeta>> {
  const r = await restFetch<MetadataResponse>(context, `/projects/${context.projectId}/workitems/${context.workItemId}/actions/getFieldsMetadata`);
  const fields: Record<string, FieldMeta> = {};
  for (const part of ["attributes", "relationships"] as const) {
    for (const [id, f] of Object.entries(r.data[part] ?? {})) {
      fields[id] = { id, label: f.label ?? id, part, type: f.type };
    }
  }
  return fields;
}

/** Relationship targets the form can offer, with the list request that fills the select. */
export const RELATIONSHIP_SOURCES: Record<string, (context: PolarionContext) => string> = {
  users: () => "/users?fields[users]=name&sort=name&page[size]=100",
  plans: (context) => `/projects/${context.projectId}/plans?fields[plans]=name&page[size]=100`,
};

/** How the form edits a field of this type, or null when the example does not support it. */
export function inputFor(meta: FieldMeta): "select" | "text" | "textarea" | "date" | "datetime" | "checkbox" | null {
  const { kind, targetResourceTypes } = meta.type;
  if (kind === "relationship") return targetResourceTypes?.length === 1 && RELATIONSHIP_SOURCES[targetResourceTypes[0]] ? "select" : null;
  switch (kind) {
    case "enumeration":
      return "select";
    case "string":
    case "duration": // for example "1d 4h"
      return "text";
    case "text":
      return "textarea";
    case "date":
      return "date";
    case "date-time":
      return "datetime";
    case "boolean":
      return "checkbox";
    default:
      return null; // structures, tables and other kinds: edit them in the form
  }
}

/** Converts the form's string value into the JSON:API shape the field expects. */
export function toJsonApi(meta: FieldMeta, value: string): unknown {
  const { kind, multi, targetResourceTypes } = meta.type;
  if (kind === "relationship") {
    const ref = { type: targetResourceTypes![0], id: value };
    return { data: multi ? [ref] : ref };
  }
  switch (kind) {
    case "enumeration":
      return multi ? [value] : value;
    case "text":
      return { type: "text/plain", value };
    case "date-time":
      return new Date(value).toISOString();
    case "boolean":
      return value === "true";
    default:
      return value;
  }
}

/** True when a value read from the REST API counts as not filled in. */
export function isEmpty(value: unknown): boolean {
  if (value === undefined || value === null || value === "") return true;
  if (Array.isArray(value)) return value.length === 0;
  if (typeof value === "object" && "value" in value) return isEmpty((value as { value: unknown }).value);
  return false;
}

/** An enumeration option as Polarion shows it: display name, icon and color. */
export interface EnumOption {
  id: string;
  name: string;
  iconURL?: string;
  color?: string;
}

interface OptionsResponse {
  data?: EnumOption[];
}

/** The selected option of an enumeration field of the current work item, for example its status. */
export async function loadCurrentOption(context: PolarionContext, fieldId: string): Promise<EnumOption | null> {
  const r = await restFetch<OptionsResponse>(context, `/projects/${context.projectId}/workitems/${context.workItemId}/fields/${fieldId}/actions/getCurrentOptions`);
  return r.data?.[0] ?? null;
}

/** All options of an enumeration field for one work item type, by id. Status names differ per type. */
export async function loadOptionsForType(context: PolarionContext, fieldId: string, type: string): Promise<Map<string, EnumOption>> {
  const r = await restFetch<OptionsResponse>(context, `/projects/${context.projectId}/workitems/fields/${fieldId}/actions/getAvailableOptions?type=${encodeURIComponent(type)}`);
  return new Map((r.data ?? []).map((o) => [o.id, o]));
}
src/components/RequiredFields.tsx
import { useEffect, useState } from "react";
import type { PolarionContext } from "polarion-app-sdk";
import { restFetch } from "../polarion";
import { inputFor, RELATIONSHIP_SOURCES, type FieldMeta } from "../fields";

interface Props {
  context: PolarionContext;
  /** The required fields of the action that are still empty, with their metadata. */
  fields: FieldMeta[];
  values: Record<string, string>;
  onChange: (field: string, value: string) => void;
}

interface Option {
  id: string;
  name: string;
}

interface ListResponse {
  data?: { id: string; name?: string; attributes?: { name?: string } }[];
}

/**
 * One input per required field, chosen from the field's metadata, so any built-in or custom
 * field works without code changes. Select options come from Polarion as well:
 * - enumerations: GET …/workitems/{id}/fields/{fieldId}/actions/getAvailableOptions
 * - relationships: the list of the target resources (users, plans; see RELATIONSHIP_SOURCES)
 */
export default function RequiredFields({ context, fields, values, onChange }: Props) {
  const [options, setOptions] = useState<Record<string, Option[]>>({});

  useEffect(() => {
    let cancelled = false;
    const base = `/projects/${context.projectId}/workitems/${context.workItemId}`;
    for (const field of fields) {
      if (inputFor(field) !== "select") continue;
      // A real application would search large lists (for example users with `query`) instead of loading 100.
      const url = field.type.kind === "relationship" ? RELATIONSHIP_SOURCES[field.type.targetResourceTypes![0]](context) : `${base}/fields/${field.id}/actions/getAvailableOptions`;
      restFetch<ListResponse>(context, url)
        .then((r) => (r.data ?? []).map((o) => ({ id: o.id, name: o.name ?? o.attributes?.name ?? o.id })))
        .catch(() => [] as Option[])
        .then((list) => {
          if (!cancelled) setOptions((o) => ({ ...o, [field.id]: list }));
        });
    }
    return () => {
      cancelled = true;
    };
  }, [context, fields]);

  return (
    <div className="required">
      {fields.map((field) => {
        const value = values[field.id] ?? "";
        const set = (v: string) => onChange(field.id, v);
        let input;
        switch (inputFor(field)) {
          case "select":
            input = options[field.id] ? (
              <select value={value} onChange={(e) => set(e.target.value)}>
                <option value="">Choose…</option>
                {options[field.id].map((o) => (
                  <option key={o.id} value={o.id}>
                    {o.name}
                  </option>
                ))}
              </select>
            ) : (
              <span className="muted">Loading…</span>
            );
            break;
          case "textarea":
            input = <textarea rows={2} value={value} onChange={(e) => set(e.target.value)} />;
            break;
          case "date":
            input = <input type="date" value={value} onChange={(e) => set(e.target.value)} />;
            break;
          case "datetime":
            input = <input type="datetime-local" value={value} onChange={(e) => set(e.target.value)} />;
            break;
          case "checkbox":
            input = <input type="checkbox" checked={value === "true"} onChange={(e) => set(String(e.target.checked))} />;
            break;
          case "text":
            input = <input value={value} onChange={(e) => set(e.target.value)} placeholder={field.type.kind === "duration" ? "for example 1d 4h" : ""} />;
            break;
          default:
            input = <span className="muted">Not editable here ({field.type.kind}); set it in the work item form.</span>;
        }
        return (
          <label key={field.id} className="row">
            <span className="field-name">{field.label}</span>
            {input}
          </label>
        );
      })}
    </div>
  );
}
src/components/CommentForm.tsx
import { useState } from "react";
import type { PolarionContext } from "polarion-app-sdk";
import { restFetch } from "../polarion";
import type { ActionState } from "../types";

interface Props {
  context: PolarionContext;
}

function escapeHtml(text: string): string {
  return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}

/** Adds a comment through POST …/workitems/{id}/comments. Comment text is HTML. */
export default function CommentForm({ context }: Props) {
  const [text, setText] = useState("");
  const [state, setState] = useState<ActionState>({ kind: "idle" });

  async function add() {
    setState({ kind: "saving" });
    try {
      await restFetch(context, `/projects/${context.projectId}/workitems/${context.workItemId}/comments`, {
        method: "POST",
        body: JSON.stringify({
          data: [
            {
              type: "workitem_comments",
              attributes: { text: { type: "text/html", value: `<p>${escapeHtml(text)}</p>` } },
            },
          ],
        }),
      });
      setText("");
      setState({ kind: "ok", text: "Comment added. Reload the page to see it in the Comments section." });
    } catch (e) {
      setState({ kind: "error", text: e instanceof Error ? e.message : String(e) });
    }
  }

  return (
    <>
      <h2>Add comment</h2>
      <textarea rows={3} value={text} onChange={(e) => setText(e.target.value)} placeholder="Comment text" />
      <div className="row">
        <button onClick={add} disabled={state.kind === "saving" || text.trim() === ""}>
          {state.kind === "saving" ? "Saving…" : "Add comment"}
        </button>
      </div>
      {state.kind === "ok" && <p className="ok">{state.text}</p>}
      {state.kind === "error" && <p className="err">{state.text}</p>}
    </>
  );
}

Comments are a sub-resource of the work item. The text is HTML, so user input is escaped before it is wrapped in a paragraph.

Note

After any write, the Polarion form around the panel still shows the old values until the page is reloaded; the framework has no refresh call yet. The messages say so.

Build and deploy

cd examples/work-item-card
npm install
npm run package          # → com.example.workitemcard.zip

Upload the ZIP, then add the applicationView element to a form layout. Open a work item that has links to see the full card.

Things to try

Examples

Project dashboard

The Project dashboard page with a query box, stat tiles, three bar charts and a table

Aspect Details
Folder examples/project-dashboard
Identifier com.example.dashboard
View navigation topic dashboard with icon
Placement <applicationView id="p-examples-project-dashboard-com.example.dashboard.dashboard"/> in the project's Topics configuration
Uses fetchContext(), REST GET …/workitems?query=…&fields[workitems]=…,assignee&page[size]=100

Source: the project is in examples/project-dashboard/ of this kit.

What it does

  1. Fetches the context for projectId.
  2. Loads up to 100 work items with id, title, status, type, created and the assignee relationship, optionally filtered by a Lucene query the user types.
  3. Renders four tiles (items loaded, not resolved, distinct types, unassigned), three bar charts built from plain <div>s (by status, by type, by assignee), and a table of the ten most recently created items with links.
  4. Apply runs the typed query and Reset goes back to all work items; Refresh repeats the applied query, shows Refreshing… while it runs and the time of the last refresh afterwards.

Files

manifest.json

manifest.json
{
  "manifestVersion": "1.0",
  "identifier": "com.example.dashboard",
  "title": "Project dashboard",
  "description": "A navigation topic that summarises the work items of the current project.",
  "publisherName": "Example Publisher",
  "applicationVersion": "0.2.1",
  "views": {
    "navigationTopics": [
      {
        "identifier": "dashboard",
        "title": "Project dashboard",
        "icon": "icon30.png",
        "rootDirectory": "dashboard",
        "document": "index.html"
      }
    ]
  }
}

src/types.ts

The assignee is a relationship, not an attribute. Asking for it in fields[workitems] makes the API include relationships.assignee.data, a list of user references.

src/types.ts
/** Minimal JSON:API shapes used by this example. */

export interface WorkItemResource {
  /** "PROJECT/WI-ID" */
  id: string;
  type: "workitems";
  attributes: { title: string; status: string; type: string; created?: string };
  /** Relationships are only present when requested through `fields[workitems]`. */
  relationships?: {
    assignee?: { data?: { id: string; type: "users" }[] };
  };
}

export interface WorkItemListResponse {
  data: WorkItemResource[];
  meta?: { totalCount?: number };
}

src/App.tsx

src/App.tsx
import { useCallback, useEffect, useRef, useState } from "react";
import { destroy, fetchContext, type PolarionContext } from "polarion-app-sdk";
import { restFetch } from "./polarion";
import type { WorkItemListResponse, WorkItemResource } from "./types";

const CLOSED_STATUSES = new Set(["resolved", "done", "closed", "verified", "rejected"]);

/** First assignee id, or "unassigned". The relationship is absent when the field was not requested. */
function assigneeOf(item: WorkItemResource): string {
  const data = item.relationships?.assignee?.data;
  return data && data.length > 0 ? data[0].id : "unassigned";
}

function countBy(items: WorkItemResource[], key: (item: WorkItemResource) => string): [string, number][] {
  const counts = new Map<string, number>();
  for (const item of items) {
    const k = key(item);
    counts.set(k, (counts.get(k) ?? 0) + 1);
  }
  return [...counts.entries()].sort((a, b) => b[1] - a[1]);
}

/** A horizontal bar chart made of plain <div>s. */
function Bars({ title, data }: { title: string; data: [string, number][] }) {
  const max = Math.max(1, ...data.map(([, n]) => n));
  return (
    <div className="panel">
      <h2>{title}</h2>
      {data.length === 0 && <p className="muted">No data.</p>}
      {data.map(([label, n]) => (
        <div className="bar-row" key={label}>
          <span className="bar-label" title={label}>
            {label}
          </span>
          <div className="bar-track">
            <div className="bar" style={{ width: `${(n / max) * 100}%` }} />
          </div>
          <span className="bar-value">{n}</span>
        </div>
      ))}
    </div>
  );
}

export default function App() {
  const [context, setContext] = useState<PolarionContext | null>(null);
  const [items, setItems] = useState<WorkItemResource[] | null>(null);
  const [total, setTotal] = useState<number | undefined>(undefined);
  const [query, setQuery] = useState("");
  const [appliedQuery, setAppliedQuery] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [loadedAt, setLoadedAt] = useState<Date | null>(null);

  // Apply and Refresh can start a load while another one runs; only the latest may update the page.
  const requestRef = useRef(0);

  const load = useCallback(async (ctx: PolarionContext, lucene: string) => {
    if (!ctx.projectId) {
      setError("No project in context. This view is meant to be opened inside a project.");
      return;
    }
    const params = new URLSearchParams({
      "fields[workitems]": "id,title,status,type,created,assignee",
      "page[size]": "100",
    });
    if (lucene.trim() !== "") {
      params.set("query", lucene.trim());
    }
    const request = ++requestRef.current;
    const isCurrent = () => request === requestRef.current;
    setLoading(true);
    try {
      // `no-store` makes Refresh always reach the server instead of a cached response.
      const response = await restFetch<WorkItemListResponse>(ctx, `/projects/${ctx.projectId}/workitems?${params}`, { cache: "no-store" });
      if (!isCurrent()) return;
      // The query counts as applied only once it has loaded, so a failed Apply never labels old data.
      setAppliedQuery(lucene);
      setItems(response.data);
      setTotal(response.meta?.totalCount);
      setLoadedAt(new Date());
      setError(null);
    } catch (error) {
      if (!isCurrent()) return;
      console.error("Unable to load the work items:", error);
      const message = error instanceof Error ? error.message : String(error);
      setError(`Unable to load the work items: ${message}`);
    } finally {
      if (isCurrent()) setLoading(false);
    }
  }, []);

  useEffect(() => {
    let cancelled = false;

    fetchContext()
      .then((ctx) => {
        if (cancelled) {
          return;
        }
        setContext(ctx);
        return load(ctx, "");
      })
      .catch((error: unknown) => {
        if (cancelled) {
          return;
        }
        console.error("Unable to fetch the Polarion context:", error);
        const message = error instanceof Error ? error.message : String(error);
        setError(`Unable to fetch the Polarion context: ${message}`);
      });

    return () => {
      // Ignore pending results before destroy() cancels requests, including during Strict Mode cleanup.
      cancelled = true;
      destroy();
    };
  }, [load]);

  function apply() {
    if (!context) return;
    void load(context, query);
  }

  /** Back to the initial state: no query, all work items of the project. */
  function reset() {
    if (!context) return;
    setQuery("");
    void load(context, "");
  }

  if (!context || !context.projectId) {
    return error ? <div className="panel error">{error}</div> : <p className="muted">Loading work items…</p>;
  }
  if (!items && !error) {
    return <p className="muted">Loading work items…</p>;
  }
  // After a failed query or request the dashboard stays mounted, so the user can
  // correct the query or press Refresh; the error is shown inline below the query row.
  const loaded = items ?? [];

  const open = loaded.filter((i) => !CLOSED_STATUSES.has((i.attributes.status ?? "").toLowerCase())).length;
  const types = new Set(loaded.map((i) => i.attributes.type)).size;
  const unassigned = loaded.filter((i) => assigneeOf(i) === "unassigned").length;
  const recent = [...loaded].sort((a, b) => (b.attributes.created ?? "").localeCompare(a.attributes.created ?? "")).slice(0, 10);
  const origin = window.location.origin;

  return (
    <div className="page">
      <header>
        <h1>Project {context.projectId}</h1>
        {/* Refresh repeats the applied query; the time below shows that it ran even when nothing changed. */}
        <button onClick={() => load(context, appliedQuery)} disabled={loading}>
          {loading ? "Refreshing…" : "Refresh"}
        </button>
      </header>

      {/* Any Lucene query that works in the Work Items table works here too. */}
      <div className="query-row">
        <input value={query} onChange={(e) => setQuery(e.target.value)} onKeyDown={(e) => e.key === "Enter" && apply()} placeholder="Lucene query, for example: type:task AND NOT status:done" />
        <button onClick={apply}>Apply</button>
        <button onClick={reset} disabled={query === "" && appliedQuery === ""}>
          Reset
        </button>
      </div>
      {error && <div className="panel error">{error}</div>}
      <p className="muted small">
        {loaded.length} loaded{total !== undefined ? ` of ${total}` : ""}
        {appliedQuery ? ` for "${appliedQuery}"` : ""} (first 100 shown)
        {loadedAt ? `, refreshed at ${loadedAt.toLocaleTimeString()}` : ""}
      </p>

      <div className="tiles">
        <div className="tile">
          <span className="value">{loaded.length}</span>
          <span className="label">work items loaded</span>
        </div>
        <div className="tile">
          <span className="value">{open}</span>
          <span className="label">not resolved</span>
        </div>
        <div className="tile">
          <span className="value">{unassigned}</span>
          <span className="label">unassigned</span>
        </div>
        <div className="tile">
          <span className="value">{types}</span>
          <span className="label">distinct types</span>
        </div>
      </div>

      <div className="charts">
        <Bars title="By status" data={countBy(loaded, (i) => i.attributes.status)} />
        <Bars title="By type" data={countBy(loaded, (i) => i.attributes.type)} />
        <Bars title="By assignee" data={countBy(loaded, assigneeOf)} />
      </div>

      <div className="panel">
        <h2>Most recently created</h2>
        <table>
          <thead>
            <tr>
              <th>ID</th>
              <th>Title</th>
              <th>Type</th>
              <th>Status</th>
              <th>Assignee</th>
              <th>Created</th>
            </tr>
          </thead>
          <tbody>
            {recent.map((item) => {
              const [project, id] = item.id.split("/");
              return (
                <tr key={item.id}>
                  <td>
                    <a href={`${origin}/polarion/#/project/${project}/workitem?id=${id}`} target="_top">
                      {id}
                    </a>
                  </td>
                  <td>{item.attributes.title}</td>
                  <td>{item.attributes.type}</td>
                  <td>{item.attributes.status}</td>
                  <td>{assigneeOf(item)}</td>
                  <td>{item.attributes.created?.slice(0, 10)}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

Points worth noting:

Build and deploy

cd examples/project-dashboard
npm install
npm run package          # → com.example.dashboard.zip

Upload the ZIP. In the project, open Administration → Portal → Topics, choose the View (Default), add the applicationView element among the topics, save, and reload the project. Project dashboard appears in the navigation panel.

Topics configuration with the dashboard added

Things to try

Examples

Release checklist

The Release checklist sidebar next to the Work Items table, listing findings per selected item

Aspect Details
Folder examples/release-checklist
Identifier com.example.releasechecklist
View sidebar checklist
Endpoints POST validate, POST assign-to-me
Placement none; choose Release checklist in the Show Sidebar menu
Uses fetchContext(), selection-changed events, your own endpoints with a JSON array in the body, the tracker and security services on the server

Source: the project is in examples/release-checklist/ of this kit.

This is the most complete example in the guide: a view that follows the user, and server-side capability that the REST API does not offer in one call. It shows the typical shape of a rich application: the sidebar is the experience, the endpoints are the capability.

What it does

  1. The sidebar fetches the context and subscribes to selection changes, debounced by 200 ms.
  2. For the selected ids it calls the application's own validate endpoint with { "objectId": "test/TEST-514", "objectIds": "[\"test/TEST-514\", …]" }: objectId is mandatory on every call, and the list is JSON-encoded into a string because Polarion accepts only string values in a POST body.
  3. validate.js runs on the server: it loads each work item, applies five rules (empty description, no assignee, no links, no priority, open for more than 90 days) and returns findings per item plus a summary. Fifty selected items are still one request. The endpoints accept at most 100 ids per call, so the view sends larger selections in chunks of 100 and merges the reports.
  4. The sidebar renders a summary strip with a chip per finding code and one card per item.
  5. Assign unassigned to me calls the assign-to-me endpoint with the ids that have the unassigned finding. assign-to-me.js adds the calling user as assignee and saves; the sidebar then re-validates.

Files

manifest.json

A sidebar view and two POST endpoints:

manifest.json
{
  "manifestVersion": "1.0",
  "identifier": "com.example.releasechecklist",
  "title": "Release checklist",
  "description": "A sidebar that checks the selected work items against release rules computed by the application's own server-side endpoints, and can assign items to the current user.",
  "publisherName": "Example Publisher",
  "applicationVersion": "0.2.2",
  "views": {
    "sidebars": [
      {
        "identifier": "checklist",
        "title": "Release checklist",
        "rootDirectory": "checklist",
        "document": "index.html",
        "menuIcon": "icon16.png",
        "icon": "icon32.png"
      }
    ]
  },
  "serverScripts": {
    "endpoints": [
      {
        "urlPath": "validate",
        "method": "POST",
        "script": "validate.js"
      },
      {
        "urlPath": "assign-to-me",
        "method": "POST",
        "script": "assign-to-me.js"
      }
    ]
  }
}

The contract

The request and response shapes are declared once, in TypeScript, and used by the view. Together with the README they are the documentation of the endpoints.

src/types.ts
/** Shapes returned by the application's own endpoints (server-scripts/). */

export type FindingCode = "no-description" | "unassigned" | "no-links" | "missing-priority" | "open-too-long" | "not-found";

export interface Finding {
  code: FindingCode;
  message: string;
}

export interface ItemResult {
  /** "PROJECT/WI-ID" */
  id: string;
  title: string;
  status: string | null;
  findings: Finding[];
}

/** POST validate */
export interface ValidateResult {
  results: ItemResult[];
  summary: {
    items: number;
    withFindings: number;
    byCode: Partial<Record<FindingCode, number>>;
  };
}

/** POST assign-to-me */
export interface AssignResult {
  updated: string[];
  failed: { id: string; error: string }[];
}

export const FINDING_LABELS: Record<FindingCode, string> = {
  "no-description": "No description",
  "unassigned": "Unassigned",
  "no-links": "No links",
  "missing-priority": "No priority",
  "open-too-long": "Open > 90 days",
  "not-found": "Not readable",
};

server-scripts/validate.js

server-scripts/validate.js
// POST /polarion/apps/com.example.releasechecklist/rest/validate
// Body: { "objectId": "PROJECT/WI-ID", "objectIds": "[\"PROJECT/WI-ID\", …]" }
//   objectId is mandatory on every endpoint call; the list travels as a JSON string
//   because POST bodies accept string values only.
//
// Checks each work item against a few release rules on the server and returns
// the findings in one response. Runs as the logged-in user; items the user may
// not read come back with a `not-found` finding.
//
// Response (inside Polarion's { timestamp, success, data } envelope):
//   { results: [ { id, title, status, findings: [ { code, message } ] } ],
//     summary: { items, withFindings, byCode: { code: count } } }

const trackerService = context.scriptContext().services().tracker();
let result = {};

// Polarion's IArguments is the script-level `arguments`; inside a function the
// name refers to the function's own arguments, so capture it once at the top.
const scriptArguments = arguments;

const NINETY_DAYS_MS = 90 * 24 * 60 * 60 * 1000;
const RESOLVED_STATUSES = ['resolved', 'done', 'closed', 'verified', 'rejected'];

const MAX_OBJECT_IDS = 100;
const OBJECT_ID = /^[^/\s]+\/[^/\s]+$/;

/**
 * Reads `objectIds`: a JSON array of "PROJECT/WI-ID" strings, sent as a string because POST bodies
 * accept string values only. Returns [{ id, projectId, workItemId }]; throws on any other input.
 */
function readObjectIds() {
  // getAsString throws "Argument objectIds is missing" when the view did not send it.
  const raw = scriptArguments.getAsString('objectIds');
  let list;
  try {
    list = JSON.parse(raw);
  } catch (e) {
    throw new Error('objectIds must be a JSON array of "PROJECT/WI-ID" strings');
  }
  if (!Array.isArray(list) || list.length === 0) {
    throw new Error('objectIds must be a non-empty JSON array of "PROJECT/WI-ID" strings');
  }
  if (list.length > MAX_OBJECT_IDS) {
    throw new Error('objectIds: at most ' + MAX_OBJECT_IDS + ' items per call');
  }
  return list.map(function (id) {
    if (typeof id !== 'string' || !OBJECT_ID.test(id)) {
      throw new Error('objectIds: expected "PROJECT/WI-ID", got ' + JSON.stringify(id));
    }
    const parts = id.split('/');
    return { id: id, projectId: parts[0], workItemId: parts[1] };
  });
}

function isEmptyText(text) {
  if (text === null || text === undefined) return true;
  const content = text.getContent ? text.getContent() : String(text);
  return content === null || String(content).replace(/<[^>]*>/g, '').trim() === '';
}

function checkItem(wi) {
  const findings = [];
  const statusId = wi.getStatus() ? String(wi.getStatus().getId()).toLowerCase() : '';

  if (isEmptyText(wi.getDescription())) {
    findings.push({ code: 'no-description', message: 'The description is empty.' });
  }
  if (wi.getAssignees().isEmpty()) {
    findings.push({ code: 'unassigned', message: 'Nobody is assigned.' });
  }
  const direct = wi.getLinkedWorkItemsStructsDirect().toArray();
  const back = wi.getLinkedWorkItemsStructsBack().toArray();
  if (direct.length === 0 && back.length === 0) {
    findings.push({ code: 'no-links', message: 'The item has no links in either direction.' });
  }
  if (wi.getPriority() === null || wi.getPriority() === undefined) {
    findings.push({ code: 'missing-priority', message: 'No priority is set.' });
  }
  const created = wi.getCreated();
  if (created && RESOLVED_STATUSES.indexOf(statusId) === -1) {
    const createdDate = new Date(created.getTime());
    if (Date.now() - createdDate.getTime() > NINETY_DAYS_MS) {
      findings.push({ code: 'open-too-long', message: 'Open for more than 90 days.' });
    }
  }
  return findings;
}

try {
  const ids = readObjectIds();

  const results = [];
  const byCode = {};
  let withFindings = 0;

  for (let i = 0; i < ids.length; i++) {
    const entry = { id: ids[i].id, title: '', status: null, findings: [] };
    try {
      const wi = trackerService.getWorkItem(ids[i].projectId, ids[i].workItemId);
      if (wi.isUnresolvable()) {
        throw new Error('not found');
      }
      entry.title = wi.getTitle();
      entry.status = wi.getStatus() ? wi.getStatus().getName() : null;
      entry.findings = checkItem(wi);
    } catch (e) {
      entry.findings = [{ code: 'not-found', message: 'Could not read the work item: ' + e }];
    }
    if (entry.findings.length > 0) withFindings++;
    for (let f = 0; f < entry.findings.length; f++) {
      const code = entry.findings[f].code;
      byCode[code] = (byCode[code] || 0) + 1;
    }
    results.push(entry);
  }

  result = {
    results: results,
    summary: { items: results.length, withFindings: withFindings, byCode: byCode },
  };
} catch (e) {
  // An `error` key turns the response into an error response for the caller.
  result = { error: 'validate failed: ' + e };
}

result;

Points worth noting:

server-scripts/assign-to-me.js

server-scripts/assign-to-me.js
// POST /polarion/apps/com.example.releasechecklist/rest/assign-to-me
// Body: { "objectId": "PROJECT/WI-ID", "objectIds": "[\"PROJECT/WI-ID\", …]" }
//   objectId is mandatory on every endpoint call; the list travels as a JSON string
//   because POST bodies accept string values only.
//
// Adds the calling user as assignee of every listed work item and saves.
// Runs as the logged-in user, who needs permission to modify the items.
//
// API calls to check against the javadoc of your Polarion version:
//   ISecurityService.getCurrentUser()            -> user id of the caller
//   ITrackerService.getProjectsService()         -> IProjectService
//   IProjectService.getUser(String)              -> IUser
//   IWorkItem.getAssignees(), addAssignee(IUser), save()
//
// Response: { updated: [ids], failed: [ { id, error } ] }

const services = context.scriptContext().services();
const trackerService = services.tracker();
const securityService = services.security();
let result = {};

// Polarion's IArguments is the script-level `arguments`; inside a function the
// name refers to the function's own arguments, so capture it once at the top.
const scriptArguments = arguments;

const MAX_OBJECT_IDS = 100;
const OBJECT_ID = /^[^/\s]+\/[^/\s]+$/;

/**
 * Reads `objectIds`: a JSON array of "PROJECT/WI-ID" strings, sent as a string because POST bodies
 * accept string values only. Returns [{ id, projectId, workItemId }]; throws on any other input.
 */
function readObjectIds() {
  // getAsString throws "Argument objectIds is missing" when the view did not send it.
  const raw = scriptArguments.getAsString('objectIds');
  let list;
  try {
    list = JSON.parse(raw);
  } catch (e) {
    throw new Error('objectIds must be a JSON array of "PROJECT/WI-ID" strings');
  }
  if (!Array.isArray(list) || list.length === 0) {
    throw new Error('objectIds must be a non-empty JSON array of "PROJECT/WI-ID" strings');
  }
  if (list.length > MAX_OBJECT_IDS) {
    throw new Error('objectIds: at most ' + MAX_OBJECT_IDS + ' items per call');
  }
  return list.map(function (id) {
    if (typeof id !== 'string' || !OBJECT_ID.test(id)) {
      throw new Error('objectIds: expected "PROJECT/WI-ID", got ' + JSON.stringify(id));
    }
    const parts = id.split('/');
    return { id: id, projectId: parts[0], workItemId: parts[1] };
  });
}

try {
  const ids = readObjectIds();

  const userId = securityService.getCurrentUser();
  const user = trackerService.getProjectsService().getUser(userId);
  if (!user || user.isUnresolvable()) {
    throw new Error('Current user not found: ' + userId);
  }

  const updated = [];
  const failed = [];
  for (let i = 0; i < ids.length; i++) {
    const id = ids[i];
    try {
      const wi = trackerService.getWorkItem(id.projectId, id.workItemId);
      if (wi.isUnresolvable()) throw new Error('not found');
      let already = false;
      const assignees = wi.getAssignees().toArray();
      for (let a = 0; a < assignees.length; a++) {
        if (String(assignees[a].getId()) === String(userId)) already = true;
      }
      if (!already) {
        wi.addAssignee(user);
        wi.save();
      }
      updated.push(id.id);
    } catch (e) {
      failed.push({ id: id.id, error: String(e) });
    }
  }

  result = { updated: updated, failed: failed };
} catch (e) {
  result = { error: 'assign-to-me failed: ' + e };
}

result;

The write endpoint resolves the calling user through the security service, loops over the items, saves each, and reports updated and failed lists rather than aborting on the first error.

Note

The comment at the top of the script lists the Java API calls it relies on. All of them were exercised against a Polarion 2612 server; verify them against the javadoc when your version differs.

src/App.tsx

src/App.tsx
import { useCallback, useEffect, useRef, useState } from "react";
import { destroy, events, EventTypes, fetchContext, type PolarionContext, type SelectionChangedData } from "polarion-app-sdk";
import { endpointFetch } from "./polarion";
import { FINDING_LABELS, type AssignResult, type FindingCode, type ItemResult, type ValidateResult } from "./types";

/** Selection ids may arrive as "WI-1" or "PROJECT/WI-1"; the endpoints expect "PROJECT/WI-1". */
function fullId(projectId: string, id: string): string {
  return id.includes("/") ? id : `${projectId}/${id}`;
}

// The endpoints accept at most 100 ids per call (MAX_OBJECT_IDS in the server scripts),
// while the table can select more. Larger selections are sent in chunks of 100.
const MAX_IDS_PER_CALL = 100;

function chunk<T>(list: T[]): T[][] {
  const parts: T[][] = [];
  for (let i = 0; i < list.length; i += MAX_IDS_PER_CALL) parts.push(list.slice(i, i + MAX_IDS_PER_CALL));
  return parts;
}

/** Joins the reports of several validate calls into one. */
function mergeReports(parts: ValidateResult[]): ValidateResult {
  const byCode: ValidateResult["summary"]["byCode"] = {};
  for (const part of parts) {
    for (const [code, n] of Object.entries(part.summary.byCode) as [FindingCode, number][]) {
      byCode[code] = (byCode[code] ?? 0) + n;
    }
  }
  return {
    results: parts.flatMap((p) => p.results),
    summary: {
      items: parts.reduce((sum, p) => sum + p.summary.items, 0),
      withFindings: parts.reduce((sum, p) => sum + p.summary.withFindings, 0),
      byCode,
    },
  };
}

function itemUrl(id: string): string {
  const [project, wi] = id.split("/");
  return `${window.location.origin}/polarion/#/project/${project}/workitem?id=${wi}`;
}

function ItemCard({ item }: { item: ItemResult }) {
  const wiId = item.id.split("/")[1] ?? item.id;
  return (
    <div className={`box item${item.findings.length === 0 ? " clean" : ""}`}>
      <div className="item-head">
        <a href={itemUrl(item.id)} target="_top">
          {wiId}
        </a>
        {item.status && <span className="chip status">{item.status}</span>}
      </div>
      <div className="item-title">{item.title || <span className="muted">(no title)</span>}</div>
      {item.findings.length === 0 ? (
        <div className="finding ok">✓ Ready for release</div>
      ) : (
        <ul className="findings">
          {item.findings.map((f) => (
            <li key={f.code} className={`finding code-${f.code}`}>
              <span className="chip warn">{FINDING_LABELS[f.code] ?? f.code}</span> {f.message}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

export default function App() {
  const [context, setContext] = useState<PolarionContext | null>(null);
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [report, setReport] = useState<ValidateResult | null>(null);
  const [busy, setBusy] = useState<"idle" | "checking" | "assigning">("idle");
  const [error, setError] = useState<string | null>(null);
  const [notice, setNotice] = useState<string | null>(null);

  // 1. Context (initial selection) and 2. selection events.
  useEffect(() => {
    let cancelled = false;

    fetchContext()
      .then((ctx) => {
        if (cancelled) {
          return;
        }
        setContext(ctx);
        setSelectedIds(ctx.selectedWorkItemIds ?? []);
      })
      .catch((error: unknown) => {
        if (cancelled) {
          return;
        }
        console.error("Unable to fetch the Polarion context:", error);
        const message = error instanceof Error ? error.message : String(error);
        setError(`Unable to fetch the Polarion context: ${message}`);
      });

    const unsubscribe = events.subscribe<SelectionChangedData>(EventTypes.SELECTION_CHANGED, (data) => {
      setSelectedIds(data.selectedWorkItemIds ?? []);
    });

    return () => {
      // Ignore pending results before destroy() cancels requests, including during Strict Mode cleanup.
      cancelled = true;
      // Remove the subscription and release the message listener.
      unsubscribe();
      destroy();
    };
  }, []);

  // 3. Ask our own endpoint to validate the selected items.
  const validate = useCallback(async (ctx: PolarionContext, ids: string[], isCurrent: () => boolean = () => true) => {
    if (!ctx.projectId || ids.length === 0) {
      setReport(null);
      return;
    }
    setBusy("checking");
    setError(null);
    try {
      const objectIds = ids.map((id) => fullId(ctx.projectId!, id));
      // `objectId` is required by Polarion on every endpoint call; the list travels
      // in `objectIds` as a JSON string (POST bodies accept string values only).
      const parts = await Promise.all(
        chunk(objectIds).map((part) =>
          endpointFetch<ValidateResult>(ctx, "/validate", {
            method: "POST",
            body: JSON.stringify({ objectId: part[0], objectIds: JSON.stringify(part) }),
          }),
        ),
      );
      if (isCurrent()) setReport(mergeReports(parts));
    } catch (error) {
      if (!isCurrent()) return;
      console.error("Unable to validate the selection:", error);
      const message = error instanceof Error ? error.message : String(error);
      setError(`Unable to validate the selection: ${message}`);
    } finally {
      if (isCurrent()) setBusy("idle");
    }
  }, []);

  // Debounce: wait until the selection has been stable for 200 ms. A request
  // that is still running when the selection changes again is ignored on return.
  // The old report is dropped at once, so its "Assign" button cannot act on the
  // previous selection while the new one is being validated.
  const requestRef = useRef(0);
  const recheck = useCallback(
    (ctx: PolarionContext, ids: string[]) => {
      const request = ++requestRef.current;
      return validate(ctx, ids, () => request === requestRef.current);
    },
    [validate],
  );
  // Counts selection changes, so work started for one selection can tell that it is outdated.
  const selectionRef = useRef(0);
  useEffect(() => {
    if (!context) return;
    ++selectionRef.current;
    ++requestRef.current;
    setReport(null);
    setNotice(null);
    const timer = setTimeout(() => void recheck(context, selectedIds), 200);
    return () => clearTimeout(timer);
  }, [context, selectedIds, recheck]);

  async function assignToMe() {
    if (!context || !report) return;
    const ids = report.results.filter((r) => r.findings.some((f) => f.code === "unassigned")).map((r) => r.id);
    if (ids.length === 0) return;
    const selection = selectionRef.current;
    setBusy("assigning");
    setNotice(null);
    setError(null);
    try {
      const parts = await Promise.all(
        chunk(ids).map((part) =>
          endpointFetch<AssignResult>(context, "/assign-to-me", {
            method: "POST",
            body: JSON.stringify({ objectId: part[0], objectIds: JSON.stringify(part) }),
          }),
        ),
      );
      const updated = parts.flatMap((p) => p.updated);
      const failed = parts.flatMap((p) => p.failed);
      setNotice(`${updated.length} item(s) assigned to you` + (failed.length ? `, ${failed.length} failed: ${failed[0].error}` : "."));
      // Re-validate only if the selection is still the one that was assigned; otherwise the
      // new selection's own validation owns the report.
      if (selection === selectionRef.current) await recheck(context, selectedIds);
    } catch (error) {
      console.error("Unable to assign the work items:", error);
      const message = error instanceof Error ? error.message : String(error);
      setError(`Unable to assign the work items: ${message}`);
    } finally {
      setBusy("idle");
    }
  }

  if (!context && !error) {
    return <p className="muted">Waiting for the Polarion context…</p>;
  }

  const unassignedCount = report?.summary.byCode.unassigned ?? 0;
  const codes = report ? (Object.keys(report.summary.byCode) as FindingCode[]) : [];

  return (
    <div>
      <p className="headline">Release checklist</p>
      {error && <div className="box error">{error}</div>}

      {selectedIds.length === 0 ? (
        <div className="box hint">Select one or more work items in the table to check them.</div>
      ) : (
        <>
          <div className="box summary">
            <div className="summary-line">{busy === "checking" ? "Checking…" : report ? `${report.summary.items} checked, ${report.summary.withFindings} with findings` : `${selectedIds.length} selected`}</div>
            {codes.length > 0 && (
              <div className="chips">
                {codes.map((code) => (
                  <span key={code} className="chip warn">
                    {FINDING_LABELS[code] ?? code}: {report!.summary.byCode[code]}
                  </span>
                ))}
              </div>
            )}
            <div className="actions">
              <button onClick={() => context && recheck(context, selectedIds)} disabled={busy !== "idle"}>
                Re-check
              </button>
              <button onClick={assignToMe} disabled={busy !== "idle" || unassignedCount === 0}>
                {busy === "assigning" ? "Assigning…" : `Assign unassigned to me (${unassignedCount})`}
              </button>
            </div>
            {notice && <div className="muted small">{notice}</div>}
          </div>

          {report?.results.map((item) => (
            <ItemCard key={item.id} item={item} />
          ))}
        </>
      )}
    </div>
  );
}

Points worth noting:

Build and deploy

cd examples/release-checklist
npm install
npm run package          # → com.example.releasechecklist.zip (with server-scripts/)

Upload the ZIP. Open a project's Work Items table, click Show Sidebar and choose Release checklist. Select a few items; the findings appear after a moment.

Things to try

Reference

manifest.json

manifest.json sits at the root of the application folder inside the ZIP. Polarion reads it during upload and whenever it needs to serve or place a view.

Complete example

manifest.json
{
  "manifestVersion": "1.0",
  "identifier": "com.example.inspector",
  "title": "Work item inspector",
  "description": "Shows details and links of the selected work items.",
  "publisherName": "Example Publisher",
  "applicationVersion": "1.2.0",
  "views": {
    "formExtensions": [
      {
        "identifier": "card",
        "title": "Inspector",
        "rootDirectory": "card",
        "document": "index.html"
      }
    ],
    "sidebars": [
      {
        "identifier": "sidebar",
        "title": "Inspector",
        "rootDirectory": "sidebar",
        "document": "index.html",
        "menuIcon": "icon16.png",
        "icon": "icon32.png"
      }
    ],
    "navigationTopics": [
      {
        "identifier": "overview",
        "title": "Inspector overview",
        "icon": "icon30.png",
        "rootDirectory": "overview",
        "document": "index.html"
      }
    ]
  },
  "serverScripts": {
    "endpoints": [
      { "urlPath": "linked-tree", "method": "GET", "script": "linked-tree.js" },
      { "urlPath": "add-comment", "method": "POST", "script": "add-comment.js" }
    ]
  }
}

Top-level fields

Field Type Required Description
manifestVersion string yes Version of the manifest format. "1.0" in Polarion 2612.
identifier string yes Unique identifier of the application on the server. Must equal the name of the top-level folder in the ZIP. Used in URLs (/polarion/apps/<identifier>/) and as the prefix of every configuration id. Reverse-DNS style recommended.
title string yes Human-readable name. Shown on the Applications tile, in the upload dialog and in Properties.
description string no Longer text. Shown as the tile tooltip and in Properties.
publisherName string yes Organization or team that publishes the application. Shown in the upload dialog and in Properties as Publisher.
applicationVersion string yes Free-form version string. Shown in the upload dialog (and compared visually with the installed version on update) and in Properties. Not parsed.
views object yes The views of the application. See below. At least one view is expected.
serverScripts object no Endpoints backed by server scripts. See below.

views

views is an object with up to three arrays. Each array may be empty or omitted.

Key View type Placed by
formExtensions Panel in the Work Item form <applicationView> in the form layout
sidebars Sidebar next to the Work Items table and in Documents Nothing; listed in Show Sidebar automatically
navigationTopics Page in the project navigation <applicationView> in the Topics configuration

Common view fields

Field Type Required Description
identifier string yes Id of the view, unique within the application. Combined with the application identifier into the configuration id <identifier>.<viewId> and the view URL /polarion/apps/<identifier>/views/<viewId>.
title string yes Display name. Used as the menu label for sidebars and the navigation label for topics. For form extensions the panel heading comes from the layout's label attribute instead.
rootDirectory string yes Folder inside the application folder that holds the view's files. One path segment, no slashes. Several views may share one folder (verified on Polarion 2612); the Application context example serves a form extension, a sidebar and a navigation topic from one.
document string yes Entry file inside rootDirectory, usually index.html.

Additional fields per view type

Field Applies to Description
menuIcon sidebars 16 × 16 px image shown in the Show Sidebar menu. Path relative to rootDirectory.
icon sidebars, navigationTopics Image shown in the sidebar header (32 × 32 px) or the navigation panel (30 × 30 px, like Polarion's own topic icons). Path relative to rootDirectory. Accepted on formExtensions but apparently not displayed in 2612.

serverScripts.endpoints

An array of endpoint definitions. Each endpoint maps an HTTP method and path to a script file.

Field Type Required Description
urlPath string yes Last path segment of the endpoint URL: /polarion/apps/<identifier>/rest/<urlPath>. Letters, digits and hyphens. Unique per method.
method "GET" | "POST" yes HTTP method the endpoint accepts. GET reads parameters from the query string; POST from a JSON body.
script string yes File name inside server-scripts/.

The runtime available to scripts is described in Server script runtime.

Validation rules

Violations are reported in the upload dialog as Application validation failed with a message, or as Application's zip structure is incorrect for layout problems.

Minimal manifest

{
  "manifestVersion": "1.0",
  "identifier": "com.example.hello",
  "title": "Hello Polarion",
  "publisherName": "Example Publisher",
  "applicationVersion": "0.1.0",
  "views": {
    "formExtensions": [
      { "identifier": "hello", "title": "Hello Polarion", "rootDirectory": "hello", "document": "index.html" }
    ]
  }
}

Reference

SDK API

Package: polarion-app-sdk, version 0.5.2-preview. Entry module HostBridge (ESM and CommonJS). No runtime dependencies. Browser only; it uses window.parent.postMessage.

import {
  fetchContext,
  events,
  destroy,
  EventTypes,
  type PolarionContext,
  type SelectionChangedData,
} from 'polarion-app-sdk';

fetchContext()

function fetchContext(): Promise<PolarionContext>

Requests the current context from the Polarion host page.

events.subscribe()

events.subscribe<T = unknown>(
  eventName: EventType,
  callback: (data: T) => void,
): () => void

Registers callback for an event emitted by the host and returns a function that removes the registration.

const unsubscribe = events.subscribe<SelectionChangedData>(
  EventTypes.SELECTION_CHANGED,
  ({ selectedWorkItemIds }) => update(selectedWorkItemIds),
);

destroy()

function destroy(): void

Tears down the gateway: removes the message listener, rejects pending fetchContext() promises with Error('ApplicationGateway is destroyed, pending request cancelled.'), sends an unsubscribe for every active subscription, and clears them. Safe to call when nothing was created. The next fetchContext() or events.subscribe() creates a new instance.

Call it from the unmount hook of your framework.

EventTypes

const EventTypes = {
  SELECTION_CHANGED: 'selection-changed',
} as const;
type EventType = typeof EventTypes[keyof typeof EventTypes];

Types

PolarionContext

interface PolarionContext {
  applicationId: string;
  viewId: string;
  projectId?: string;
  spaceId?: string;
  documentId?: string;
  workItemId?: string;
  selectedWorkItemIds: string[];
  appEndpoint: string;
  restBaseUrl: string;
  restToken?: string;
}

Described field by field in PolarionContext.

SelectionChangedData

interface SelectionChangedData {
  selectedWorkItemIds: string[];
}

Work item ids with the project ("test/TEST-514"), observed on Polarion 2612 in the Work Items table and in Documents. Empty array when nothing is selected.

Behavior notes

Internal modules (not public API)

ApplicationGateway, Constants (Actions, MessageTypes) and the protocol types in types/ApplicationGatewayProtocol describe the postMessage protocol (polarion-view-bridge, polarion-view-bridge-result, polarion-view-bridge-event). They are exported as type declarations for transparency but may change without notice. Do not post these messages yourself.

Reference

PolarionContext

The object returned by fetchContext(), field by field.

interface PolarionContext {
  applicationId: string;
  viewId: string;
  projectId?: string;
  spaceId?: string;
  documentId?: string;
  workItemId?: string;
  selectedWorkItemIds: string[];
  appEndpoint: string;
  restBaseUrl: string;
  restToken?: string;
}

Fields

applicationId

The identifier from the manifest of the application that owns the view. Always set.

viewId

The identifier of the view (from views.*[].identifier). Always set. Together with applicationId it tells a shared code base which view is running.

projectId

Id of the project the view is shown in, for example "test". Set for all view types inside a project. Undefined only in places without a project context (none of the three view types in 2612 are placed outside a project).

spaceId, documentId

Space and name of the Document, set (according to the SDK documentation) when the view is shown inside a Document: a sidebar opened in the Document editor, or a form extension in a work item form opened from a Document. Undefined elsewhere. Use them to build the REST URL …/projects/{projectId}/spaces/{spaceId}/documents/{documentId}.

workItemId

Project-local id of the work item whose form contains the view, for example "TEST-514". Set for form extensions. Undefined for sidebars and navigation topics, and in the create form of a work item that is not saved yet.

selectedWorkItemIds

Array of work item ids with the project, for example "test/TEST-514". Always present, possibly empty.

View type Content
Form extension The open work item, ["<projectId>/<workItemId>"]. In the multi-item edit form below the Work Items table: all ticked items, while workItemId is the current one.
Sidebar Empty on Polarion 2612, even when rows are selected. The selection arrives through selection-changed events.
Navigation topic Empty.

appEndpoint

Absolute base URL of the application's server-script endpoints, without trailing slash:

https://<host>/polarion/apps/<applicationId>/rest

Append /<urlPath> for each endpoint declared in the manifest. Set even when the application declares no endpoints.

restBaseUrl

Absolute base URL of the Polarion REST API, without trailing slash:

https://<host>/polarion/rest/v1

restToken

Token that authenticates REST and endpoint calls as the current user. Send it in the required X-Polarion-REST-Token header on every REST and endpoint call. Application endpoints cannot authenticate through the browser session or cookies. Undefined or empty when the server has not enabled REST token authentication (com.siemens.polarion.rest.security.restApiToken.enabled). Treat it as a credential: memory only, same origin only.

Example values

Form extension on a Task:

{
  "applicationId": "com.example.context",
  "viewId": "form",
  "projectId": "test",
  "workItemId": "TEST-514",
  "selectedWorkItemIds": ["test/TEST-514"],
  "appEndpoint": "https://polarion.example.com/polarion/apps/com.example.context/rest",
  "restBaseUrl": "https://polarion.example.com/polarion/rest/v1",
  "restToken": "UE9M…"
}

Sidebar in the Work Items table with two rows selected (the selection comes through events, not here):

{
  "applicationId": "com.example.selectionsidebar",
  "viewId": "selection",
  "projectId": "test",
  "selectedWorkItemIds": [],
  "appEndpoint": "https://polarion.example.com/polarion/apps/com.example.selectionsidebar/rest",
  "restBaseUrl": "https://polarion.example.com/polarion/rest/v1",
  "restToken": "UE9M…"
}

Navigation topic:

{
  "applicationId": "com.example.dashboard",
  "viewId": "dashboard",
  "projectId": "test",
  "selectedWorkItemIds": [],
  "appEndpoint": "https://polarion.example.com/polarion/apps/com.example.dashboard/rest",
  "restBaseUrl": "https://polarion.example.com/polarion/rest/v1",
  "restToken": "UE9M…"
}

Validation performed by the SDK

fetchContext() only checks that applicationId and viewId are strings. All other fields are passed through as delivered by the host. Code defensively against undefined optional fields.

Reference

Endpoint runtime

This page describes the environment a server script runs in. Observed behavior on Polarion 2612 is stated as fact; details marked as expected should be checked against your server.

Request mapping

GET endpoint POST endpoint
URL /polarion/apps/<identifier>/rest/<urlPath>?a=1&b=2 /polarion/apps/<identifier>/rest/<urlPath>
Parameters Query string Flat JSON object with string values in the request body; Content-Type: application/json required. Arrays or objects as values are rejected with HTTP 500 (Expected a string but was BEGIN_ARRAY).
Reading a parameter arguments.getAsString('a') arguments.getAsString('a')
Authentication Valid X-Polarion-REST-Token header required; sessions and cookies do not authenticate endpoint calls Same requirement
Intended for Reads Writes and anything with side effects

A POST without a JSON content type or without a parseable body is expected to be rejected with HTTP 400 before the script runs. Parameters sent in the query string of a POST are not visible to the script.

objectId is mandatory on every call (GET or POST). Without it Polarion answers HTTP 400 Argument objectId is missing in workflow definition before the script runs. Use PROJECT/WI-ID of the object the call concerns, or a project id.

Globals

context

Entry point to the Polarion scripting API.

Expression Returns
context.scriptContext() IScriptContext
context.scriptContext().services() IScriptServices: tracker(), security(), project(), …
context.scriptContext().utils() IScriptUtils: httpClient(), …

services().tracker() is ITrackerService, the usual way to reach work items:

const trackerService = context.scriptContext().services().tracker();
const wi = trackerService.getWorkItem(projectId, workItemId);   // IWorkItem
const project = trackerService.getTrackerProject(projectId);    // ITrackerProject

services().security() is ISecurityService; see the javadoc for the accessor of the current user.

arguments

Polarion's IArguments object with the request parameters, available under the name arguments at the top level of the script. Inside a function the name refers to the function's own arguments object, so capture it first: const scriptArguments = arguments;.

Method Description
getAsString(name) The parameter as a string. Throws Argument name is missing in workflow definition when the parameter was not sent; the call then fails with HTTP 400. Wrap reads of optional parameters in try/catch.
getAsString(name, default) Variant with a default value, as listed for IArguments in the scripting API; check the javadoc of your version. The examples use a guarded helper instead.
getAsInt(name), getAsBoolean(name), … Typed variants as documented for IArguments in the scripting API.

Structured input must be sent as a JSON-encoded string and parsed with JSON.parse.

Java

GraalVM's interop object. Java.type('fully.qualified.Name') loads a Polarion or JDK class:

const Text = Java.type('com.polarion.core.util.types.Text');
const comment = wi.createComment(Text.plain('Reviewed.'), 'My app', null);

Working with Java objects

Result and envelope

The script's last expression is the result. It must be a plain JavaScript object, array or primitive that can be serialized to JSON. Polarion wraps it:

{ "timestamp": "2026-10-05T10:15:42.945Z", "success": true, "data": <result> }

If the result object contains a non-empty error property, or the script throws, the envelope becomes:

{ "timestamp": "…", "success": false, "error": "<message>" }

A successful script returns HTTP 200. A script that returned { error }, threw, or read a missing parameter returns HTTP 400 with the envelope; a body with non-string values returns HTTP 500. The table below summarizes what was observed on Polarion 2612.

HTTP status Body Cause
200 { timestamp, success: true, data } Script completed
400 { timestamp, success: false, error } Script returned an error key or threw
400 { error: "Argument objectId is missing in workflow definition." } objectId not sent, or arguments.getAsString() on an absent parameter
500 { error: "… Expected a string but was BEGIN_ARRAY …" } POST body contains an array or object value
401 REST error document Missing, invalid or expired X-Polarion-REST-Token, even if a Polarion session exists
404 HTML or error document Unknown urlPath, wrong method, application not installed

Permissions and transactions

Logging

console.log() output is expected in the Polarion server log. Keep it sparse; the log is shared by the whole server.

Limits

Further reading

Reference

View configuration XML

Form extensions and navigation topics are placed with the applicationView element in Polarion's configuration XML. Sidebars need no XML.

Form layout (formLayout)

Location: Project Administration → Work Items → Form Configuration → Form Layouts → Edit (per work item type and Polarion View). Repository-level defaults: Global Administration → Work Items → Form Configuration.

<applicationView id="com.example.workitemcard.card" label="Work item card" height="640px"/>
Attribute Required Description
id yes <application identifier>.<view identifier> of a formExtensions view
label no Heading of the panel. Default Polarion Application.
height no CSS height of the iframe (320px, 50vh).

Placement: a direct child of <formLayout>, in document order with <field>, <horizontal>, <vertical> and <extension> elements. Not allowed inside <section> or <panel>.

Full example:

<?xml version="1.0" encoding="UTF-8"?>
<formLayout xmlns="http://polarion.com/schema/WorkItems/FormLayout"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://polarion.com/schema/WorkItems/FormLayout">
  <horizontal>
    <vertical>
      <section>
        <field id="type"/>
        <field id="severity"/>
        <field id="author"/>
      </section>
    </vertical>
    <vertical>
      <section>
        <field id="assignee"/>
        <field id="priority"/>
        <field id="status"/>
      </section>
    </vertical>
  </horizontal>
  <applicationView id="com.example.workitemcard.card" label="Work item card" height="640px"/>
  <field id="description"/>
  <applicationView id="com.example.traceability.tree" label="Traceability" height="480px"/>
  <field id="comments"/>
  <field id="linkedWorkItems"/>
  <field id="attachments"/>
</formLayout>

Topics configuration (topics)

Location: Project Administration → Portal → Topics → (View). Repository-level defaults: Global Administration → Portal → Topics.

<applicationView id="com.example.dashboard.dashboard"/>
Attribute Required Description
id yes <application identifier>.<view identifier> of a navigationTopics view

Placement: a direct child of <topics>, among <topic> elements. Order determines the position in the navigation panel.

<?xml version="1.0" encoding="UTF-8"?>
<topics xmlns="http://polarion.com/schema/Portal/Topics"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://polarion.com/schema/Portal/Topics">
  <topic id="workitems"/>
  <topic id="wiki"/>
  <topic id="plans"/>
  <topic id="testruns"/>
  <topic id="collections"/>
  <topic id="baselines"/>
  <topic id="builds"/>
  <topic id="reports"/>
  <topic id="monitor"/>
  <applicationView id="com.example.dashboard.dashboard"/>
  <topic id="global_shortcuts"/>
  <topic id="project_shortcuts"/>
  <topic id="user_shortcuts"/>
</topics>

Sidebars

No XML. The sidebar is opened from the Show Sidebar menu and remembered in the page URL:

?sidebar=polarion-application.<application identifier>.<view identifier>

Example: /polarion/#/project/test/workitems?sidebar=polarion-application.com.example.selectionsidebar.selection

Validation

Polarion does not appear to validate the referenced application or view when saving the XML; a wrong id results in an empty or failing panel. Check Global Administration → Applications → Properties for the installed identifier and the manifest for the view identifier when a panel does not appear.

Reference

Configuration properties

The properties below control the Applications feature and the REST authentication that views depend on.

Property Where Restart Effect
polarionapp.enabled Global Administration → Configuration Properties (global configuration property, not a polarion.properties entry) no true enables the Applications feature: the Applications topic in Global Administration, serving of /polarion/apps/…, and the host bridge in the UI. Default false.
com.siemens.polarion.rest.enabled polarion.properties yes Enables the REST API. Required for views that call restBaseUrl and for server script endpoints.
com.siemens.polarion.rest.security.restApiToken.enabled polarion.properties yes Enables the REST token mechanism used by application views (context.restToken, header X-Polarion-REST-Token). Without it the token is empty and REST API and application endpoint calls fail with 401. Application endpoints require the token header even if a browser session exists.

Where the files live

Uploaded applications are stored by Polarion on the server and served at /polarion/apps/<identifier>/. They are not placed in the extensions/ folder and do not require a restart.

Reference

Limitations and known issues

This page lists what the 2612 preview does not do yet and the issues to be aware of when planning an application.

Preview scope

Polarion Applications and the SDK are a preview in 2612. The feature is usable for internal applications and pilots; expect changes in later releases, in particular to the manifest format, the SDK API and the configuration elements.

SDK

Views

Server scripts

Administration

Browser support

Views run in the browsers Polarion supports. Vite's default target (modern evergreen browsers) is appropriate; no transpilation for legacy browsers is needed.

Reporting issues

Report problems with the Applications feature or the SDK through your usual Polarion support channel, quoting the Polarion build (shown on the login page), the SDK version from node_modules/polarion-app-sdk/package.json, and the manifest of the application.

Reference

Glossary

The vocabulary of Polarion Applications, in alphabetical order. Each entry links to the page where the concept is explained.

A

Application : A package (ZIP) with a manifest, one or more views and optional endpoints, uploaded to Polarion through Global Administration. The extensibility framework

Application identifier : The identifier field of the manifest; globally unique on a server and the name of the top-level folder in the ZIP. Reverse-DNS style, for example com.example.inspector. Application package

applicationView : The XML element that places a form extension in a form layout or a navigation topic in a Topics configuration. Its id is <identifier>.<viewId>. View configuration XML

appEndpoint : Context field with the base URL of the application's own endpoints: https://<host>/polarion/apps/<identifier>/rest. PolarionContext

arguments : Polarion's IArguments object inside a server script, holding the request parameters. Inside a JavaScript function the name refers to the function's own arguments, so capture it at the top level. Write the server script

C

Context : The PolarionContext object a view receives from fetchContext(): identifiers of the surrounding project, work item or document, the selection, and the URLs and token for HTTP calls. Application context

E

Endpoint : An HTTP path under /polarion/apps/<identifier>/rest/ implemented by a server script and declared in serverScripts.endpoints. Your own REST API inside Polarion. Your own REST endpoints

Envelope : The JSON wrapper { timestamp, success, data } or { timestamp, success: false, error } around every endpoint response. Results and the envelope

Event : A notification pushed by the Polarion host to a view through the SDK. Polarion 2612 emits selection-changed. React to selection changes

F

Form extension : A view type rendered as a collapsible panel inside the Work Item form; knows the open work item. Form extension

Form layout : Polarion's XML configuration of the Work Item form per work item type and Polarion View. Where form extensions are placed. Place it in a form layout

H

Host bridge : The part of the Polarion page that answers SDK requests and emits events to application iframes over postMessage. How an application works

M

manifestVersion : Manifest field with the version of the manifest format; "1.0" in Polarion 2612. manifest.json

Manifest : manifest.json, the descriptor of an application: identity, views and endpoints. manifest.json

N

Navigation topic : A view type rendered as a full page with an entry in the project navigation panel. Navigation topic

O

objectId : The parameter every endpoint call must carry, usually PROJECT/WI-ID of the object the call is about. The objectId parameter

P

Polarion View (hat) : Polarion's named sets of navigation topics and form layouts (Default and any custom ones). Not to be confused with an application view.

Polarion Application SDK : The npm package polarion-app-sdk providing fetchContext, events, destroy and EventTypes. SDK API

publisherName : Manifest field naming the organization that publishes the application; shown in the upload dialog and in Properties. manifest.json

R

REST API : Polarion's documented REST API under /polarion/rest/v1, callable from a view with the token from the context. Calling the REST API from a view

REST token : The value of context.restToken, sent as the X-Polarion-REST-Token header to authenticate REST and endpoint calls as the current user. Requires token authentication on the server. Enable Applications in Polarion

Root directory : The folder of a view inside the application package (rootDirectory in the manifest). Application package

S

Selection : The work items currently selected in a Work Items table or Document. Sidebars receive it only through the selection-changed event; their context.selectedWorkItemIds is empty. A form extension gets the open item, or all ticked items in the multi-item edit form, in context.selectedWorkItemIds. React to selection changes

Server script : A JavaScript file in server-scripts/ executed on the Polarion server by GraalVM when its endpoint is called; has access to the Polarion Java API. Write the server script

Sidebar : A view type shown in the sidebar area next to the Work Items table and in Documents, selectable from the Show Sidebar menu. Sidebar

T

Topics configuration : Polarion's XML configuration of the navigation panel per Polarion View. Where navigation topics are placed. Add it to the navigation

V

View : One web page of an application placed at one kind of location in Polarion: form extension, sidebar or navigation topic. Declared under views in the manifest. Views

View identifier : The identifier of a view, unique within its application. Combined with the application identifier into <identifier>.<viewId>. manifest.json

Reference

Cheat sheet

Everything on this page was verified on Polarion 2612. Follow the links for the details.

URLs

What URL
Static files of an application https://<host>/polarion/apps/<identifier>/<rootDirectory>/<file>
View entry (redirects to the view's document) https://<host>/polarion/apps/<identifier>/views/<viewId>
Application endpoint https://<host>/polarion/apps/<identifier>/rest/<urlPath>
REST API https://<host>/polarion/rest/v1/…
Navigation topic page https://<host>/polarion/#/project/<projectId>/<identifier>.<viewId>
Work Items table with a sidebar open …/#/project/<projectId>/workitems?sidebar=polarion-application.<identifier>.<viewId>
SDK download https://<host>/polarion/sdk/applications/polarion-app-sdk-0.5.2-preview.tgz

Configuration XML

<!-- Form layout: Project Administration → Work Items → Form Configuration → Form Layouts -->
<applicationView id="<identifier>.<viewId>" label="Panel heading" height="480px"/>

<!-- Topics: Project Administration → Portal → Topics → <View> -->
<applicationView id="<identifier>.<viewId>"/>

<!-- Sidebars: no XML; listed in Show Sidebar automatically -->

Package layout

Server settings

# Global Administration → Configuration Properties (global configuration property)
polarionapp.enabled=true                                      # Applications feature

# polarion.properties (restart required)
com.siemens.polarion.rest.enabled=true                        # REST API (else 503)
com.siemens.polarion.rest.security.restApiToken.enabled=true  # token for views (else warning dialog, 401)

SDK

import { fetchContext, events, EventTypes, destroy } from 'polarion-app-sdk';
const context = await fetchContext();                       // 5 s timeout outside Polarion
const stop = events.subscribe(EventTypes.SELECTION_CHANGED, ({ selectedWorkItemIds }) => {});
stop(); destroy();                                          // on unmount

context.restBaseUrl and context.appEndpoint have no trailing slash. workItemId is project-local (DP-477); selectedWorkItemIds and selection events carry the project (drivepilot/DP-477).

REST call

fetch(`${context.restBaseUrl}/projects/${p}/workitems/${id}?fields[workitems]=id,title,status`, {
  headers: { 'X-Polarion-REST-Token': context.restToken!, Accept: 'application/json' },
});

Sparse field sets also filter relationships: fields[linkedworkitems]=role,suspect,workItem.

Endpoint rules

  1. Every call carries objectId (PROJECT/WI-ID), in the query string (GET) or the body (POST).
  2. POST bodies are flat objects with string values; encode lists as JSON strings.
  3. arguments.getAsString('x') throws for an absent parameter; guard optional ones.
  4. Inside a function, arguments is JavaScript's own; capture const scriptArguments = arguments; at the top.
  5. Save what you change: wi.save() for fields, comment.save() for a new comment.
  6. The last expression is the response; an error key makes it an error (HTTP 400 with the envelope).
const trackerService = context.scriptContext().services().tracker();
const scriptArguments = arguments;
let result = {};
try {
  const [projectId, wiId] = scriptArguments.getAsString('objectId').split('/');
  const wi = trackerService.getWorkItem(projectId, wiId);
  result = { id: wi.getId(), title: wi.getTitle() };
} catch (e) {
  result = { error: 'my-endpoint failed: ' + e };
}
result;

Upload dialog

Install: identity + SHA-2 hash (128 hex digits). Update: New Version next to Current Version. Delete: immediate, no visible confirmation.