Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🌿 feat: Accept Lane Git State and Pull Request Contract- #16792 (#16792)
Marco Beretta22b1d4f966cd
diff --git a/packages/api/src/code/workspace.spec.ts b/packages/api/src/code/workspace.spec.tsindex 2abcf3e18a..69e64b4db5 100644--- a/packages/api/src/code/workspace.spec.ts+++ b/packages/api/src/code/workspace.spec.ts@@ -1970,6 +1970,76 @@ describe('executeWorkspaceTool', () => {).resolves.toMatchObject({ exitCode: 2, stderr: 'not found' });});+ describe('lane git on command results', () => {+ const commandResult = {+ protocolVersion: 1,+ operation: 'execute_command',+ workspaceId: 'primary',+ exitCode: 0,+ stdout: '',+ stderr: '',+ truncated: false,+ timedOut: false,+ };+ const run = (extra: Record<string, unknown>) =>+ executeWorkspaceTool({+ baseURL: 'https://code.example.com/v1',+ authHeaders: {},+ request: {+ protocolVersion: 1,+ operation: 'execute_command',+ workspaceId: 'primary',+ command: 'git status',+ },+ fetchImpl: jest.fn(async () => Response.json({ ...commandResult, ...extra })),+ });+ const head40 = 'a'.repeat(40);+ const head64 = 'b'.repeat(64);++ test('passes a branch and head through unchanged', async () => {+ await expect(+ run({ laneGit: { branch: 'feat/pr-chip', head: head40 } }),+ ).resolves.toMatchObject({ laneGit: { branch: 'feat/pr-chip', head: head40 } });+ });++ test('accepts a null branch and head for a detached or empty lane', async () => {+ await expect(run({ laneGit: { branch: null, head: null } })).resolves.toMatchObject({+ laneGit: { branch: null, head: null },+ });+ });++ test('accepts a 64 character head and a 256 character branch', async () => {+ const branch = 'x'.repeat(256);+ await expect(run({ laneGit: { branch, head: head64 } })).resolves.toMatchObject({+ laneGit: { branch, head: head64 },+ });+ });++ test('leaves laneGit absent when the worker did not send it', async () => {+ const result = await run({});+ expect(result).not.toHaveProperty('laneGit');+ });++ test.each<[string, unknown]>([+ ['an extra key', { branch: 'main', head: head40, path: '/srv/repo' }],+ ['a missing head', { branch: 'main' }],+ ['a missing branch', { head: head40 }],+ ['an empty branch', { branch: '', head: head40 }],+ ['a branch over 256 characters', { branch: 'x'.repeat(257), head: head40 }],+ ['a control character in the branch', { branch: 'main\nrm', head: head40 }],+ ['a DEL character in the branch', { branch: 'main\x7f', head: head40 }],+ ['an uppercase head', { branch: 'main', head: 'A'.repeat(40) }],+ ['a short head', { branch: 'main', head: 'a'.repeat(39) }],+ ['a non-hex head', { branch: 'main', head: 'g'.repeat(40) }],+ ['a numeric branch', { branch: 7, head: head40 }],+ ['an array', [null, null]],+ ['a string', 'main'],+ ['null', null],+ ])('rejects the result when laneGit has %s', async (_label, laneGit) => {+ await expect(run({ laneGit })).rejects.toMatchObject({ reason: 'invalid' });+ });+ });+test('rejects command requests and results outside protocol limits', async () => {const fetchImpl: CodeBridgeFetch = jest.fn(async () =>Response.json({diff --git a/packages/api/src/code/workspace.ts b/packages/api/src/code/workspace.tsindex 120718bf10..f7ab968ae0 100644--- a/packages/api/src/code/workspace.ts+++ b/packages/api/src/code/workspace.ts@@ -35,6 +35,7 @@ export const WORKSPACE_COMMAND_MAX_TIMEOUT_MS: number = 5 * 60_000;const DEFAULT_COMMAND_OUTPUT_BYTES = 256 * 1024;const MAX_COMMAND_OUTPUT_BYTES = 1024 * 1024;const MAX_COMMAND_SIGNAL_LENGTH = 32;+const MAX_LANE_BRANCH_LENGTH = 256;const WORKSPACE_COMMAND_TRANSPORT_GRACE_MS = 5_000;/** Legacy per-request admission window, independent of the retry horizon. */const WORKSPACE_QUEUE_TIMEOUT_MS = 30_000;@@ -100,7 +101,9 @@ const COMMAND_RESULT_KEYS = new Set(['stderr','truncated','timedOut',+ 'laneGit',]);+const LANE_GIT_KEYS = new Set(['branch', 'head']);const WRITE_RESULT_KEYS = new Set(['protocolVersion','operation',@@ -264,6 +267,14 @@ export interface WorkspaceExecuteCommandResult {stderr: string;truncated: boolean;timedOut: boolean;+ /** Branch and head of the lane the command ran in. Absent means unknown, null means the lane+ * has no branch (detached) or no commit yet. */+ laneGit?: WorkspaceLaneGit;+}++export interface WorkspaceLaneGit {+ branch: string | null;+ head: string | null;}export interface WorkspaceWriteResult {@@ -661,6 +672,27 @@ function areValidEditMatches();}+function hasControlCharacter(value: string): boolean {+ for (let index = 0; index < value.length; index++) {+ const code = value.charCodeAt(index);+ if (code <= 0x1f || code === 0x7f) return true;+ }+ return false;+}++function isLaneGit(value: unknown): value is WorkspaceLaneGit {+ if (!isRecord(value) || !hasOnlyKeys(value, LANE_GIT_KEYS)) return false;+ const { branch, head } = value;+ return (+ (branch === null ||+ (typeof branch === 'string' &&+ branch.length >= 1 &&+ branch.length <= MAX_LANE_BRANCH_LENGTH &&+ !hasControlCharacter(branch))) &&+ (head === null || (typeof head === 'string' && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(head)))+ );+}+function hasOnlyKeys(value: Record<string, unknown>, allowed: ReadonlySet<string>): boolean {return Object.keys(value).every((key) => allowed.has(key));}@@ -916,6 +948,7 @@ function isValidResult(const outputLimit = request.maxOutputBytes ?? DEFAULT_COMMAND_OUTPUT_BYTES;return (hasOnlyKeys(value, COMMAND_RESULT_KEYS) &&+ (!('laneGit' in value) || isLaneGit(value.laneGit)) &&typeof value.truncated === 'boolean' &&stdout != null &&stderr != null &&diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.tsindex 7432e3e506..69092d97ee 100644--- a/packages/data-provider/src/api-endpoints.ts+++ b/packages/data-provider/src/api-endpoints.ts@@ -168,6 +168,9 @@ export const backgroundTasks = (conversationId: string) =>export const backgroundTasksCancel = (conversationId: string) =>`${backgroundTasks(conversationId)}/cancel`;+export const conversationPullRequest = (conversationId: string) =>+ `${conversationsRoot}/${encodeURIComponent(conversationId)}/pull-request`;+export const genTitle = (conversationId: string) =>`${conversationsRoot}/gen_title/${encodeURIComponent(conversationId)}`;diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.tsindex 27585e536e..7123e83c4c 100644--- a/packages/data-provider/src/config.spec.ts+++ b/packages/data-provider/src/config.spec.ts@@ -1114,6 +1114,41 @@ describe('attached code environment user config schema', () => {});});+describe('agent pull request config', () => {+ const parse = (pullRequests?: unknown) =>+ configSchema.safeParse({ version: '1.0', endpoints: { agents: { pullRequests } } });++ it('is off by default and absent when not configured', () => {+ const absent = configSchema.parse({ version: '1.0', endpoints: { agents: {} } });+ expect(absent.endpoints?.agents?.pullRequests).toBeUndefined();+ const empty = configSchema.parse({+ version: '1.0',+ endpoints: { agents: { pullRequests: {} } },+ });+ expect(empty.endpoints?.agents?.pullRequests).toEqual({ enabled: false, cacheTtlSeconds: 30 });+ });++ it('accepts an enabled block with an environment variable reference', () => {+ const result = parse({ enabled: true, token: '${GITHUB_PULL_REQUEST_TOKEN}' });+ expect(result.success).toBe(true);+ });++ it('requires a token reference when enabled', () => {+ expect(parse({ enabled: true }).success).toBe(false);+ });++ it.each(['ghp_abcdef', '${bad name}', '$GITHUB_TOKEN', '${}'])(+ 'rejects %s as a token because only a reference is allowed',+ (token) => {+ expect(parse({ enabled: true, token }).success).toBe(false);+ },+ );++ it.each([4, 3601, 1.5])('rejects a cache lifetime of %s seconds', (cacheTtlSeconds) => {+ expect(parse({ cacheTtlSeconds }).success).toBe(false);+ });+});+describe('agent background completion batch config', () => {it('defaults and bounds automatic completion coalescing', () => {const defaults = configSchema.parse({diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex 2471aa8ff0..38e7fdfb27 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -498,6 +498,13 @@ const skillSyncTenantIdSchema = zmessage: 'must not be the reserved system tenant id',});+const pullRequestTokenReferenceSchema = z+ .string()+ .trim()+ .regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/, {+ message: 'must be an environment variable reference like ${GITHUB_PULL_REQUEST_TOKEN}',+ });+export const skillSyncGitHubSourceSchema = z.object({id: skillSyncIdentifierSchema,@@ -1836,6 +1843,27 @@ export const agentsEndpointSchema = baseEndpointSchema.optional(),}).optional(),+ /** Header pull request chip: finds the pull request for the branch a conversation's code+ * workspace reports, using a server-held GitHub token. Off unless an administrator opts in. */+ pullRequests: z+ .object({+ enabled: z.boolean().optional().default(false),+ /** Environment variable reference holding a read-only GitHub token, e.g.+ * `${GITHUB_PULL_REQUEST_TOKEN}`. Never the token itself. */+ token: pullRequestTokenReferenceSchema.optional(),+ /** Seconds a looked-up pull request is reused before GitHub is asked again. */+ cacheTtlSeconds: z.number().int().min(5).max(3600).optional().default(30),+ })+ .superRefine((value, ctx) => {+ if (value.enabled && !value.token) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ['token'],+ message: 'A token reference is required when pull requests are enabled',+ });+ }+ })+ .optional(),/** Conversational background-task delivery policy. Automatic completion wakeups are* enabled unless an administrator explicitly restores poll-only behavior. */backgroundTasks: zdiff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.tsindex 3fb895a94a..0898bed4ab 100644--- a/packages/data-provider/src/data-service.ts+++ b/packages/data-provider/src/data-service.ts@@ -1227,6 +1227,12 @@ export function cancelBackgroundTasks(return request.post(endpoints.backgroundTasksCancel(conversationId), body);}+export function getConversationPullRequest(+ conversationId: string,+): Promise<t.TConversationPullRequestResponse> {+ return request.get(endpoints.conversationPullRequest(conversationId));+}+export function getPrompt(id: string): Promise<{ prompt: t.TPrompt }> {return request.get(endpoints.getPrompt(id));}diff --git a/packages/data-provider/src/index.ts b/packages/data-provider/src/index.tsindex 2be4fec215..3238b8ddab 100644--- a/packages/data-provider/src/index.ts+++ b/packages/data-provider/src/index.ts@@ -64,6 +64,7 @@ export type {} from './types/protection';export * from './types/subagents';export * from './types/background';+export * from './types/pullRequest';export * from './types/queuedTurns';/* access permissions */export * from './accessPermissions';diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.tsindex d5704fef52..93d3d43919 100644--- a/packages/data-provider/src/keys.ts+++ b/packages/data-provider/src/keys.ts@@ -109,6 +109,7 @@ export enum QueryKeys {parentSubagents = 'parentSubagents',subagentThread = 'subagentThread',backgroundTasks = 'backgroundTasks',+ conversationPullRequest = 'conversationPullRequest',codeEnvironments = 'codeEnvironments',agentQueuedTurns = 'agentQueuedTurns',/* Combined Pinned-section display order (favorites + pinned chats) */diff --git a/packages/data-provider/src/pullRequest.spec.ts b/packages/data-provider/src/pullRequest.spec.tsnew file mode 100644index 0000000000..30b33710d1--- /dev/null+++ b/packages/data-provider/src/pullRequest.spec.ts@@ -0,0 +1,26 @@+import { PULL_REQUEST_CHECKS, PULL_REQUEST_MERGEABLE, PULL_REQUEST_STATES } from './types';+import { conversationPullRequest } from './api-endpoints';+import { QueryKeys } from './keys';++describe('conversation pull request contract', () => {+ it('builds the endpoint under the conversation', () => {+ expect(conversationPullRequest('abc-123')).toBe('/api/convos/abc-123/pull-request');+ });++ it('encodes a conversation id so it cannot change the path or query', () => {+ const endpoint = conversationPullRequest('a/b?c=d#e');+ expect(endpoint).toBe('/api/convos/a%2Fb%3Fc%3Dd%23e/pull-request');+ expect(endpoint).not.toContain('?');+ expect(endpoint).not.toContain('#');+ });++ it('has its own query key', () => {+ expect(QueryKeys.conversationPullRequest).toBe('conversationPullRequest');+ });++ it('lists every state the header can render', () => {+ expect([...PULL_REQUEST_STATES]).toEqual(['open', 'closed', 'merged']);+ expect([...PULL_REQUEST_MERGEABLE]).toEqual(['clean', 'conflicting', 'unknown']);+ expect([...PULL_REQUEST_CHECKS]).toEqual(['passing', 'failing', 'running', 'none']);+ });+});diff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.tsindex 2b51072af5..0e6db56cf9 100644--- a/packages/data-provider/src/types.ts+++ b/packages/data-provider/src/types.ts@@ -34,6 +34,7 @@ import type { Agent } from './types/agents';export * from './schemas';export * from './types/subagents';export * from './types/background';+export * from './types/pullRequest';export type TMessages = TMessage[];diff --git a/packages/data-provider/src/types/pullRequest.ts b/packages/data-provider/src/types/pullRequest.tsnew file mode 100644index 0000000000..0796962e56--- /dev/null+++ b/packages/data-provider/src/types/pullRequest.ts@@ -0,0 +1,28 @@+export const PULL_REQUEST_STATES = ['open', 'closed', 'merged'] as const;+export const PULL_REQUEST_MERGEABLE = ['clean', 'conflicting', 'unknown'] as const;+export const PULL_REQUEST_CHECKS = ['passing', 'failing', 'running', 'none'] as const;++export type PullRequestState = (typeof PULL_REQUEST_STATES)[number];+export type PullRequestMergeable = (typeof PULL_REQUEST_MERGEABLE)[number];+export type PullRequestChecks = (typeof PULL_REQUEST_CHECKS)[number];++/** The pull request a conversation's code workspace opened, as the chat header shows it. */+export type TConversationPullRequest = {+ number: number;+ title: string;+ /** GitHub page for the pull request. */+ url: string;+ additions: number;+ deletions: number;+ state: PullRequestState;+ isDraft: boolean;+ /** `unknown` while GitHub is still computing it, and for closed or merged pull requests. */+ mergeable: PullRequestMergeable;+ /** Rollup of the head commit's check runs; `none` when the repository has no checks. */+ checks: PullRequestChecks;+};++/** `pullRequest` is null when the conversation has no pull request, which is not an error. */+export type TConversationPullRequestResponse = {+ pullRequest: TConversationPullRequest | null;+};