Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
b1a1438
fix(onepassword): bound item patches and refuse ones that change noth…
waleedlatif1 Nov 29, 2026
7824af8
fix(mcp): accept client-posted JSON-RPC responses on workflow MCP ser…
waleedlatif1 Nov 29, 2026
cee31a6
feat(library): Google ADK vs LangGraph vs Pydantic AI: Which Is Best …
waleedlatif1 Nov 30, 2026
43667d5
feat(library): Dust vs n8n vs Gumloop for Company Knowledge and Workf…
waleedlatif1 Nov 30, 2026
7a5a3f5
feat(library): n8n vs LangChain: Which Should Teams Use for AI Agent …
waleedlatif1 Nov 30, 2026
2813d20
feat(library): Dify vs n8n: Which Should Self Hosted AI Workflow Team…
waleedlatif1 Nov 30, 2026
1f1651b
feat(library): Best Platforms for Building Internal Tools Powered by …
waleedlatif1 Nov 30, 2026
1b153f3
docs(library): update llms-vs-ai-agents (#10515)
waleedlatif1 Nov 30, 2026
1b2d2d8
docs(library): update best-workato-alternatives-ai-agents-2026 (#10516)
waleedlatif1 Nov 30, 2026
010a7ea
docs(library): update best-pipedream-alternatives-2026 (#10517)
waleedlatif1 Nov 30, 2026
397e191
docs(library): update best-microsoft-copilot-studio-power-automate-al…
waleedlatif1 Nov 30, 2026
338655f
fix(desktop-terminal): keep a fast command's output when its start an…
waleedlatif1 Nov 30, 2026
fb7d9e5
docs(library): update best-dust-alternatives-2026 (#10519)
waleedlatif1 Nov 30, 2026
09c0b11
fix(billing): refuse plan changes during a pro trial (#10520)
waleedlatif1 Nov 30, 2026
f7a153f
fix(desktop-terminal): follow alternate-screen switches in stream ord…
waleedlatif1 Nov 30, 2026
f195a22
fix(onepassword): refuse item patches whose path reaches nothing (#10…
waleedlatif1 Nov 30, 2026
7afd34d
fix(billing): hold Mothership fal video and audio generation to paid …
waleedlatif1 Nov 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions apps/desktop/src/main/terminal/session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,83 @@ describe('stripTerminalQueries', () => {
})

describe('TerminalSession command lifecycle', () => {
it('returns the output of a command whose start, output and end arrive in one read', async () => {
const originalShell = process.env.SHELL
process.env.SHELL = '/bin/zsh'
const session = TerminalSession.create({
terminalId: 'terminal-1',
cwd: '/tmp',
cols: 80,
rows: 24,
callbacks: { onData: () => {}, onState: () => {}, onCommand: () => {}, onExit: () => {} },
})

try {
const resultPromise = session.runCommand('printf done', 'tool-call-fast', 5_000)
// A fast command's echo, start marker, output, end marker and next prompt can share one read.
ptyStub.dataHandler?.(
'printf done\r\n\u001b]633;C;test-nonce\u0007done\u001b]633;P;Cwd=/tmp;test-nonce\u0007\u001b]633;D;0;test-nonce\u0007\u001b]633;A;test-nonce\u0007% '
)
expect(await resultPromise).toMatchObject({
status: 'completed',
exitCode: 0,
output: 'done',
})
} finally {
session.dispose()
if (originalShell === undefined) process.env.SHELL = undefined
else process.env.SHELL = originalShell
}
})

it('reports a full-screen program that exits within one read as completed, with its exit code', async () => {
const originalShell = process.env.SHELL
process.env.SHELL = '/bin/zsh'
const session = TerminalSession.create({
terminalId: 'terminal-1',
cwd: '/tmp',
cols: 80,
rows: 24,
callbacks: { onData: () => {}, onState: () => {}, onCommand: () => {}, onExit: () => {} },
})

try {
const resultPromise = session.runCommand("vim -c 'cq'", 'tool-call-vim', 5_000)
ptyStub.dataHandler?.(
'\u001b]633;C;test-nonce\u0007\u001b[?1049h\u001b[?1049l\u001b]633;D;1;test-nonce\u0007\u001b]633;A;test-nonce\u0007'
)
expect(await resultPromise).toMatchObject({ status: 'completed', exitCode: 1 })
} finally {
session.dispose()
if (originalShell === undefined) process.env.SHELL = undefined
else process.env.SHELL = originalShell
}
})

it('shows a full-screen program as open when it starts in the same read the previous command ended', () => {
const originalShell = process.env.SHELL
process.env.SHELL = '/bin/zsh'
const session = TerminalSession.create({
terminalId: 'terminal-1',
cwd: '/tmp',
cols: 80,
rows: 24,
callbacks: { onData: () => {}, onState: () => {}, onCommand: () => {}, onExit: () => {} },
})

try {
// Typed-ahead `ls` then `vim`: the end of one and the start of the next can share a read.
ptyStub.dataHandler?.(
'\u001b]633;C;test-nonce\u0007a b\r\n\u001b]633;D;0;test-nonce\u0007\u001b]633;A;test-nonce\u0007% \u001b]633;C;test-nonce\u0007\u001b[?1049h'
)
expect(session.tabState(true).interactive).toBe(true)
} finally {
session.dispose()
if (originalShell === undefined) process.env.SHELL = undefined
else process.env.SHELL = originalShell
}
})

it('keeps normal long-command activity until the foreground process exits', async () => {
vi.useFakeTimers()
const originalShell = process.env.SHELL
Expand Down
46 changes: 33 additions & 13 deletions apps/desktop/src/main/terminal/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -824,31 +824,51 @@ export class TerminalSession {
}

private handleData(chunk: string): void {
const { text, markers } = this.parser.parse(chunk)

for (const marker of markers) {
this.applyMarker(marker)
}
const { text, markers, offsets } = this.parser.parse(chunk)

if (text) {
this.lastOutputAt = Date.now()
this.trackAltScreen(text)
this.scrollback += text
if (this.scrollback.length > MAX_SCROLLBACK_CHARS + TRIM_SLACK_CHARS) {
this.scrollback = this.scrollback.slice(-MAX_SCROLLBACK_CHARS)
}
if (this.pendingCommand?.capturing) {
this.pendingCommand.lastActivityAt = Date.now()
this.captureOutput(this.pendingCommand, text)
if (text.includes(ALT_SCREEN_ENTER)) {
this.resolveInteractiveCommand()
}
}
}

// Text is applied in stream order, so a command keeps only the output between its own start
// and end markers, and a screen switch lands on whichever command was running when it came.
let from = 0
let enteredFullScreen = false
markers.forEach((marker, index) => {
enteredFullScreen = this.applyText(text.slice(from, offsets[index])) || enteredFullScreen
from = offsets[index]
this.applyMarker(marker)
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
})
enteredFullScreen = this.applyText(text.slice(from)) || enteredFullScreen
// Judged once the whole read is applied: a program that opened and closed the alternate
// screen and finished within it already has its result, and one that left it is not holding it.
if (enteredFullScreen && this.pendingCommand?.capturing && this.altScreen) {
this.resolveInteractiveCommand()
}

if (text) {
this.pendingOutput += text
this.scheduleFlush()
}
}

/**
* Follows the screen switches in `text` and adds it to the running command's output; true when
* that command entered the alternate screen.
*/
private applyText(text: string): boolean {
if (!text) return false
this.trackAltScreen(text)
if (!this.pendingCommand?.capturing) return false
this.pendingCommand.lastActivityAt = Date.now()
this.captureOutput(this.pendingCommand, text)
return text.includes(ALT_SCREEN_ENTER)
}

private applyMarker(
marker: ReturnType<ShellIntegrationParser['parse']>['markers'][number]
): void {
Expand Down
14 changes: 12 additions & 2 deletions apps/desktop/src/main/terminal/shell-integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@ export interface ParseResult {
/** Stream with the OSC 633 sequences removed, safe to hand to xterm.js. */
text: string
markers: ShellMarker[]
/**
* Where each marker fell in `text`: `markers[i]` came after `text.slice(0, offsets[i])`. A fast
* command's start, output and end can share one chunk, so output belongs to a command only
* between its own markers.
*/
offsets: number[]
}

/** Undoes the escaping applied by the shell hooks. */
Expand Down Expand Up @@ -84,6 +90,7 @@ export class ShellIntegrationParser {
this.pending = ''

const markers: ShellMarker[] = []
const offsets: number[] = []
let text = ''
let index = 0

Expand All @@ -110,11 +117,14 @@ export class ShellIntegrationParser {

const body = buffer.slice(start + '\u001b]633;'.length, terminator.index)
const marker = this.toMarker(body)
if (marker) markers.push(marker)
if (marker) {
markers.push(marker)
offsets.push(text.length)
}
index = terminator.index + terminator.length
}

return { text, markers }
return { text, markers, offsets }
}

private toMarker(body: string): ShellMarker | null {
Expand Down
114 changes: 110 additions & 4 deletions apps/sim/app/api/billing/switch-plan/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,26 @@ import { authMockFns, createMockRequest, resetEnvFlagsMock, setEnvFlags } from '
import { billingAccessMock, billingAccessMockFns } from '@sim/testing/mocks/billing-access.mock'
import { billingCoreMock, billingCoreMockFns } from '@sim/testing/mocks/billing-core.mock'
import { billingOrganizationMock } from '@sim/testing/mocks/billing-organization.mock'
import { billingPlanMock } from '@sim/testing/mocks/billing-plan.mock'
import { billingPlanMock, billingPlanMockFns } from '@sim/testing/mocks/billing-plan.mock'
import { billingSubscriptionMock } from '@sim/testing/mocks/billing-subscription.mock'
import { posthogServerMock } from '@sim/testing/mocks/posthog-server.mock'
import { stripeClientMock } from '@sim/testing/mocks/stripe.mock'
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'

const { mockCanManageWorkspaceBilling, mockGetWorkspaceHostContextForViewer } = vi.hoisted(() => ({
const {
mockCanManageWorkspaceBilling,
mockGetWorkspaceHostContextForViewer,
mockClaimCheckoutAdmission,
mockReleaseCheckoutAdmission,
mockReadSwitchBasis,
mockRecordPlanSwitch,
} = vi.hoisted(() => ({
mockCanManageWorkspaceBilling: vi.fn(),
mockGetWorkspaceHostContextForViewer: vi.fn(),
mockClaimCheckoutAdmission: vi.fn(),
mockReleaseCheckoutAdmission: vi.fn(),
mockReadSwitchBasis: vi.fn(),
mockRecordPlanSwitch: vi.fn(),
}))

vi.mock('@/lib/billing/core/access', () => billingAccessMock)
Expand All @@ -22,6 +34,26 @@ vi.mock('@/lib/billing/core/plan', () => billingPlanMock)

vi.mock('@/lib/billing/core/subscription', () => billingSubscriptionMock)

vi.mock('@/lib/billing/stripe-client', () => stripeClientMock)

vi.mock('@/lib/billing/checkout-admission', () => ({
claimCheckoutAdmission: mockClaimCheckoutAdmission,
releaseCheckoutAdmission: mockReleaseCheckoutAdmission,
}))

vi.mock('@/lib/billing/plans', () => ({
getPlanByName: (name: string) => ({
name,
priceId: 'price-month',
annualDiscountPriceId: 'price-year',
}),
}))

vi.mock('@/lib/billing/core/plan-switch', () => ({
readSwitchBasis: mockReadSwitchBasis,
recordPlanSwitch: mockRecordPlanSwitch,
}))

vi.mock('@/lib/billing/workspace-permissions', () => ({
canManageWorkspaceBilling: mockCanManageWorkspaceBilling,
}))
Expand All @@ -34,7 +66,9 @@ vi.mock('@/lib/workspaces/host-context', () => ({

import { POST } from '@/app/api/billing/switch-plan/route'

const { mockGetOrganizationSubscription } = billingCoreMockFns
const { mockGetOrganizationSubscription, mockIsSubscriptionOrgScoped } = billingCoreMockFns

const routeContext = { params: Promise.resolve({}) }

const { mockGetEffectiveBillingStatus } = billingAccessMockFns

Expand Down Expand Up @@ -96,7 +130,8 @@ describe('POST /api/billing/switch-plan', () => {
createMockRequest('POST', {
targetPlanName: 'enterprise',
workspaceId: 'workspace-1',
})
}),
routeContext
)

expect(response.status).toBe(400)
Expand All @@ -105,4 +140,75 @@ describe('POST /api/billing/switch-plan', () => {
})
expect(mockGetEffectiveBillingStatus).not.toHaveBeenCalled()
})

describe('during a Pro free trial', () => {
const personalPro = (status: string) => ({
id: 'subscription-1',
referenceId: 'viewer-1',
plan: 'pro_6000',
status,
stripeSubscriptionId: 'stripe-subscription-1',
})
const mockStripeUpdate = vi.fn()

beforeEach(() => {
mockGetEffectiveBillingStatus.mockResolvedValue({
billingBlocked: false,
billingBlockedReason: null,
blockedByOrgOwner: false,
})
mockIsSubscriptionOrgScoped.mockResolvedValue(false)
mockClaimCheckoutAdmission.mockResolvedValue({ claimToken: 'claim-1' })
stripeClientMock.requireStripeClient.mockReturnValue({
subscriptions: {
retrieve: vi.fn().mockResolvedValue({
status: 'trialing',
items: {
data: [{ id: 'item-1', price: { id: 'price-1', recurring: { interval: 'month' } } }],
},
}),
update: mockStripeUpdate,
},
})
})

it.each([
{ label: 'a tier change', targetPlanName: 'pro_25000', interval: undefined },
{ label: 'an interval change', targetPlanName: 'pro_6000', interval: 'year' },
])('refuses $label before touching Stripe', async (switchCase) => {
billingPlanMockFns.mockGetHighestPrioritySubscription.mockResolvedValue(
personalPro('trialing')
)

const response = await POST(
createMockRequest('POST', {
targetPlanName: switchCase.targetPlanName,
interval: switchCase.interval,
}),
routeContext
)

expect(response.status).toBe(409)
await expect(response.json()).resolves.toMatchObject({
error: expect.stringContaining('free trial ends'),
})
expect(stripeClientMock.requireStripeClient).not.toHaveBeenCalled()
})

it('refuses a switch Stripe still holds in trial while the row has moved on', async () => {
const subscription = personalPro('active')
billingPlanMockFns.mockGetHighestPrioritySubscription.mockResolvedValue(subscription)
mockReadSwitchBasis.mockResolvedValue({ subscription, pool: undefined })

const response = await POST(
createMockRequest('POST', { targetPlanName: 'pro_6000', interval: 'year' }),
routeContext
)

expect(response.status).toBe(409)
expect(mockStripeUpdate).not.toHaveBeenCalled()
expect(mockRecordPlanSwitch).not.toHaveBeenCalled()
expect(mockReleaseCheckoutAdmission).toHaveBeenCalledWith({ claimToken: 'claim-1' })
})
})
})
15 changes: 14 additions & 1 deletion apps/sim/app/api/billing/switch-plan/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { type NextRequest, NextResponse } from 'next/server'
import { billingSwitchPlanContract } from '@/lib/api/contracts/subscription'
import { parseRequest } from '@/lib/api/server'
import { getSession } from '@/lib/auth'
import { TRIAL_PLAN_CHANGE_MESSAGE } from '@/lib/billing/authorization'
import {
type CheckoutAdmissionClaim,
claimCheckoutAdmission,
Expand All @@ -19,13 +20,14 @@ import {
getHighestPrioritySubscription,
} from '@/lib/billing/core/plan'
import { readSwitchBasis, recordPlanSwitch } from '@/lib/billing/core/plan-switch'
import { getPlanTierCredits, getPlanType, isEnterprise } from '@/lib/billing/plan-helpers'
import { getPlanTierCredits, getPlanType, isEnterprise, isPro } from '@/lib/billing/plan-helpers'
import { getPlanByName } from '@/lib/billing/plans'
import { requireStripeClient } from '@/lib/billing/stripe-client'
import {
hasUsableSubscriptionAccess,
hasUsableSubscriptionStatus,
isOrgScopedSubscription,
isTrialingSubscription,
} from '@/lib/billing/subscriptions/utils'
import { canManageWorkspaceBilling } from '@/lib/billing/workspace-permissions'
import { isBillingEnabled } from '@/lib/core/config/env-flags'
Expand Down Expand Up @@ -106,6 +108,13 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
)
}

// A Pro trial's fixed allowance is counted per billing period, and a price change restarts the
// period, so a switch during the trial would start the cap over. Pro is only ever personal.
const isProPlan = isPro(sub.plan)
if (isProPlan && isTrialingSubscription(sub)) {
return NextResponse.json({ error: TRIAL_PLAN_CHANGE_MESSAGE }, { status: 409 })
}

const targetPlan = getPlanByName(targetPlanName)
if (!targetPlan) {
return NextResponse.json({ error: 'Target plan not found' }, { status: 400 })
Expand Down Expand Up @@ -156,6 +165,10 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
if (!hasUsableSubscriptionStatus(stripeSubscription.status)) {
return NextResponse.json({ error: 'Stripe subscription is not active' }, { status: 400 })
}
// The row can trail Stripe: a trial whose start webhook has not landed is still a trial.
if (isProPlan && isTrialingSubscription(stripeSubscription)) {
return NextResponse.json({ error: TRIAL_PLAN_CHANGE_MESSAGE }, { status: 409 })
}

const subscriptionItem = stripeSubscription.items.data[0]
if (!subscriptionItem) {
Expand Down
Loading
Loading