跳到正文
cccskills
免费在 GitHub 公开

trigger-realtime

Build interfaces that follow Trigger.dev v4 task runs as they happen. The skill covers subscriptions to run status, metadata, tagged runs, and streamed data from backend code or React hooks, using scoped access tokens for reads and triggers.

中文简介正在准备中。当前显示英语简介。

原文查看原文说明

How to use realtime in your Trigger.dev tasks and your frontend

trycompai/comp星标 2,058(GitHub 2,058 + cccskills 0)
集成工具OpenAI

实测评分 未实测

查看安装方法

适用场景

  • Showing task status and progress in a React interface
  • Subscribing to runs by ID, tag, or batch
  • Displaying streamed task output as it arrives
  • Creating scoped public tokens for frontend access

包含的文件(1)

  • SKILL.md6.9 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

Source Cursor rule: .cursor/rules/trigger.realtime.mdc. Original file scope: **/trigger/**/*.ts. Original Cursor alwaysApply: false.

Trigger.dev Realtime (v4)

Real-time monitoring and updates for runs

Core Concepts

Realtime allows you to:

  • Subscribe to run status changes, metadata updates, and streams
  • Build real-time dashboards and UI updates
  • Monitor task progress from frontend and backend

Authentication

Public Access Tokens

import { auth } from "@trigger.dev/sdk";

// Read-only token for specific runs
const publicToken = await auth.createPublicToken({
  scopes: {
    read: {
      runs: ["run_123", "run_456"],
      tasks: ["my-task-1", "my-task-2"],
    },
  },
  expirationTime: "1h", // Default: 15 minutes
});

Trigger Tokens (Frontend only)

// Single-use token for triggering tasks
const triggerToken = await auth.createTriggerPublicToken("my-task", {
  expirationTime: "30m",
});

Backend Usage

Subscribe to Runs

import { runs, tasks } from "@trigger.dev/sdk";

// Trigger and subscribe
const handle = await tasks.trigger("my-task", { data: "value" });

// Subscribe to specific run
for await (const run of runs.subscribeToRun<typeof myTask>(handle.id)) {
  console.log(`Status: ${run.status}, Progress: ${run.metadata?.progress}`);
  if (run.status === "COMPLETED") break;
}

// Subscribe to runs with tag
for await (const run of runs.subscribeToRunsWithTag("user-123")) {
  console.log(`Tagged run ${run.id}: ${run.status}`);
}

// Subscribe to batch
for await (const run of runs.subscribeToBatch(batchId)) {
  console.log(`Batch run ${run.id}: ${run.status}`);
}

Streams

import { task, metadata } from "@trigger.dev/sdk";

// Task that streams data
export type STREAMS = {
  openai: OpenAI.ChatCompletionChunk;
};

export const streamingTask = task({
  id: "streaming-task",
  run: async (payload) => {
    const completion = await openai.chat.completions.create({
      model: "gpt-4",
      messages: [{ role: "user", content: payload.prompt }],
      stream: true,
    });

    // Register stream
    const stream = await metadata.stream("openai", completion);

    let text = "";
    for await (const chunk of stream) {
      text += chunk.choices[0]?.delta?.content || "";
    }

    return { text };
  },
});

// Subscribe to streams
for await (const part of runs.subscribeToRun(runId).withStreams<STREAMS>()) {
  switch (part.type) {
    case "run":
      console.log("Run update:", part.run.status);
      break;
    case "openai":
      console.log("Stream chunk:", part.chunk);
      break;
  }
}

React Frontend Usage

Installation

bun add @trigger.dev/react-hooks

Triggering Tasks

"use client";
import { useTaskTrigger, useRealtimeTaskTrigger } from "@trigger.dev/react-hooks";
import type { myTask } from "../trigger/tasks";

function TriggerComponent({ accessToken }: { accessToken: string }) {
  // Basic trigger
  const { submit, handle, isLoading } = useTaskTrigger<typeof myTask>("my-task", {
    accessToken,
  });

  // Trigger with realtime updates
  const {
    submit: realtimeSubmit,
    run,
    isLoading: isRealtimeLoading,
  } = useRealtimeTaskTrigger<typeof myTask>("my-task", { accessToken });

  return (
    <div>
      <button onClick={() => submit({ data: "value" })} disabled={isLoading}>
        Trigger Task
      </button>

      <button onClick={() => realtimeSubmit({ data: "realtime" })} disabled={isRealtimeLoading}>
        Trigger with Realtime
      </button>

      {run && <div>Status: {run.status}</div>}
    </div>
  );
}

Subscribing to Runs

"use client";
import { useRealtimeRun, useRealtimeRunsWithTag } from "@trigger.dev/react-hooks";
import type { myTask } from "../trigger/tasks";

function SubscribeComponent({ runId, accessToken }: { runId: string; accessToken: string }) {
  // Subscribe to specific run
  const { run, error } = useRealtimeRun<typeof myTask>(runId, {
    accessToken,
    onComplete: (run) => {
      console.log("Task completed:", run.output);
    },
  });

  // Subscribe to tagged runs
  const { runs } = useRealtimeRunsWithTag("user-123", { accessToken });

  if (error) return <div>Error: {error.message}</div>;
  if (!run) return <div>Loading...</div>;

  return (
    <div>
      <div>Status: {run.status}</div>
      <div>Progress: {run.metadata?.progress || 0}%</div>
      {run.output && <div>Result: {JSON.stringify(run.output)}</div>}

      <h3>Tagged Runs:</h3>
      {runs.map((r) => (
        <div key={r.id}>
          {r.id}: {r.status}
        </div>
      ))}
    </div>
  );
}

Streams with React

"use client";
import { useRealtimeRunWithStreams } from "@trigger.dev/react-hooks";
import type { streamingTask, STREAMS } from "../trigger/tasks";

function StreamComponent({ runId, accessToken }: { runId: string; accessToken: string }) {
  const { run, streams } = useRealtimeRunWithStreams<typeof streamingTask, STREAMS>(runId, {
    accessToken,
  });

  const text = streams.openai
    .filter((chunk) => chunk.choices[0]?.delta?.content)
    .map((chunk) => chunk.choices[0].delta.content)
    .join("");

  return (
    <div>
      <div>Status: {run?.status}</div>
      <div>Streamed Text: {text}</div>
    </div>
  );
}

Wait Tokens

"use client";
import { useWaitToken } from "@trigger.dev/react-hooks";

function WaitTokenComponent({ tokenId, accessToken }: { tokenId: string; accessToken: string }) {
  const { complete } = useWaitToken(tokenId, { accessToken });

  return <button onClick={() => complete({ approved: true })}>Approve Task</button>;
}

SWR Hooks (Fetch Once)

"use client";
import { useRun } from "@trigger.dev/react-hooks";
import type { myTask } from "../trigger/tasks";

function SWRComponent({ runId, accessToken }: { runId: string; accessToken: string }) {
  const { run, error, isLoading } = useRun<typeof myTask>(runId, {
    accessToken,
    refreshInterval: 0, // Disable polling (recommended)
  });

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return <div>Run: {run?.status}</div>;
}

Run Object Properties

Key properties available in run subscriptions:

  • id: Unique run identifier
  • status: QUEUED, EXECUTING, COMPLETED, FAILED, CANCELED, etc.
  • payload: Task input data (typed)
  • output: Task result (typed, when completed)
  • metadata: Real-time updatable data
  • createdAt, updatedAt: Timestamps
  • costInCents: Execution cost

Best Practices

  • Use Realtime over SWR: Recommended for most use cases due to rate limits
  • Scope tokens properly: Only grant necessary read/trigger permissions
  • Handle errors: Always check for errors in hooks and subscriptions
  • Type safety: Use task types for proper payload/output typing
  • Cleanup subscriptions: Backend subscriptions auto-complete, frontend hooks auto-cleanup

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

Guide API endpoint changes so request DTOs, runtime validation, OpenAPI documentation, and MCP tool metadata stay aligned. It covers discoverability, authentication, uploads, long-running tasks, and response types that MCP tools cannot handle.

中文简介正在准备中。当前显示英语简介。

  • Adding an API endpoint with a request body
  • Updating DTO validation and OpenAPI metadata
  • Making an endpoint available as an MCP tool
trycompai/comp20582026年10月24日 更新

Review specified files for design system usage, replace legacy @trycompai/ui components and lucide-react icons with available @trycompai/design-system equivalents, and run the app type check to verify the migration.

中文简介正在准备中。当前显示英语简介。

  • Migrating legacy UI components
  • Replacing lucide-react icons with Carbon icons
  • Checking specified files for design system compliance
trycompai/comp20582026年10月24日 更新

Review specified files for outdated hook and API patterns, then replace them with the prescribed SWR hooks, API clients, or server API calls. The guidance covers data fetching, mutations, cache updates, and response handling, followed by a typecheck command.

中文简介正在准备中。当前显示英语简介。

  • Auditing files for disallowed API and hook patterns
  • Replacing raw fetch calls with the API client
  • Migrating server actions and database mutations to API hooks
trycompai/comp20582026年10月24日 更新

Review NestJS API endpoints and frontend components for role-based access control and audit log compliance. The skill lists permission, guard, route, and UI gating rules, then directs the agent to fix violations and run type checks.

中文简介正在准备中。当前显示英语简介。

  • Auditing API routes for permission decorators
  • Checking UI actions against user permissions
  • Fixing access control inconsistencies
trycompai/comp20582026年10月24日 更新

Audit unit tests for components that use permissions. Add missing tests and fix failures, checking that administrators can use mutation controls, auditors cannot, and read-only content remains visible to both.

中文简介正在准备中。当前显示英语简介。

  • Adding permission tests for a component
  • Checking admin and auditor behavior
  • Fixing failing permission-related tests
trycompai/comp20582026年10月24日 更新

Set up Better Auth for TypeScript applications, including server and client configuration, database adapters, sessions, email and social sign-in, and plugins. The guide also highlights environment variables, schema generation, and security settings to review.

中文简介正在准备中。当前显示英语简介。

  • Configuring Better Auth in a TypeScript app
  • Connecting an ORM or database adapter
  • Setting up sessions and cookie storage
trycompai/comp20582026年10月24日 更新

查看 trycompai 的全部技能

报告此技能的问题