Skip to content

Commit 62b6433

Browse files
authored
v0.9.71: trial plan-change guard, 1password patch bounds, mcp json-rpc responses
2 parents 14d835f + 7afd34d commit 62b6433

36 files changed

Lines changed: 1878 additions & 327 deletions

File tree

‎apps/desktop/src/main/terminal/session.test.ts‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,83 @@ describe('stripTerminalQueries', () => {
7575
})
7676

7777
describe('TerminalSession command lifecycle', () => {
78+
it('returns the output of a command whose start, output and end arrive in one read', async () => {
79+
const originalShell = process.env.SHELL
80+
process.env.SHELL = '/bin/zsh'
81+
const session = TerminalSession.create({
82+
terminalId: 'terminal-1',
83+
cwd: '/tmp',
84+
cols: 80,
85+
rows: 24,
86+
callbacks: { onData: () => {}, onState: () => {}, onCommand: () => {}, onExit: () => {} },
87+
})
88+
89+
try {
90+
const resultPromise = session.runCommand('printf done', 'tool-call-fast', 5_000)
91+
// A fast command's echo, start marker, output, end marker and next prompt can share one read.
92+
ptyStub.dataHandler?.(
93+
'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% '
94+
)
95+
expect(await resultPromise).toMatchObject({
96+
status: 'completed',
97+
exitCode: 0,
98+
output: 'done',
99+
})
100+
} finally {
101+
session.dispose()
102+
if (originalShell === undefined) process.env.SHELL = undefined
103+
else process.env.SHELL = originalShell
104+
}
105+
})
106+
107+
it('reports a full-screen program that exits within one read as completed, with its exit code', async () => {
108+
const originalShell = process.env.SHELL
109+
process.env.SHELL = '/bin/zsh'
110+
const session = TerminalSession.create({
111+
terminalId: 'terminal-1',
112+
cwd: '/tmp',
113+
cols: 80,
114+
rows: 24,
115+
callbacks: { onData: () => {}, onState: () => {}, onCommand: () => {}, onExit: () => {} },
116+
})
117+
118+
try {
119+
const resultPromise = session.runCommand("vim -c 'cq'", 'tool-call-vim', 5_000)
120+
ptyStub.dataHandler?.(
121+
'\u001b]633;C;test-nonce\u0007\u001b[?1049h\u001b[?1049l\u001b]633;D;1;test-nonce\u0007\u001b]633;A;test-nonce\u0007'
122+
)
123+
expect(await resultPromise).toMatchObject({ status: 'completed', exitCode: 1 })
124+
} finally {
125+
session.dispose()
126+
if (originalShell === undefined) process.env.SHELL = undefined
127+
else process.env.SHELL = originalShell
128+
}
129+
})
130+
131+
it('shows a full-screen program as open when it starts in the same read the previous command ended', () => {
132+
const originalShell = process.env.SHELL
133+
process.env.SHELL = '/bin/zsh'
134+
const session = TerminalSession.create({
135+
terminalId: 'terminal-1',
136+
cwd: '/tmp',
137+
cols: 80,
138+
rows: 24,
139+
callbacks: { onData: () => {}, onState: () => {}, onCommand: () => {}, onExit: () => {} },
140+
})
141+
142+
try {
143+
// Typed-ahead `ls` then `vim`: the end of one and the start of the next can share a read.
144+
ptyStub.dataHandler?.(
145+
'\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'
146+
)
147+
expect(session.tabState(true).interactive).toBe(true)
148+
} finally {
149+
session.dispose()
150+
if (originalShell === undefined) process.env.SHELL = undefined
151+
else process.env.SHELL = originalShell
152+
}
153+
})
154+
78155
it('keeps normal long-command activity until the foreground process exits', async () => {
79156
vi.useFakeTimers()
80157
const originalShell = process.env.SHELL

‎apps/desktop/src/main/terminal/session.ts‎

Lines changed: 33 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -824,31 +824,51 @@ export class TerminalSession {
824824
}
825825

826826
private handleData(chunk: string): void {
827-
const { text, markers } = this.parser.parse(chunk)
828-
829-
for (const marker of markers) {
830-
this.applyMarker(marker)
831-
}
827+
const { text, markers, offsets } = this.parser.parse(chunk)
832828

833829
if (text) {
834830
this.lastOutputAt = Date.now()
835-
this.trackAltScreen(text)
836831
this.scrollback += text
837832
if (this.scrollback.length > MAX_SCROLLBACK_CHARS + TRIM_SLACK_CHARS) {
838833
this.scrollback = this.scrollback.slice(-MAX_SCROLLBACK_CHARS)
839834
}
840-
if (this.pendingCommand?.capturing) {
841-
this.pendingCommand.lastActivityAt = Date.now()
842-
this.captureOutput(this.pendingCommand, text)
843-
if (text.includes(ALT_SCREEN_ENTER)) {
844-
this.resolveInteractiveCommand()
845-
}
846-
}
835+
}
836+
837+
// Text is applied in stream order, so a command keeps only the output between its own start
838+
// and end markers, and a screen switch lands on whichever command was running when it came.
839+
let from = 0
840+
let enteredFullScreen = false
841+
markers.forEach((marker, index) => {
842+
enteredFullScreen = this.applyText(text.slice(from, offsets[index])) || enteredFullScreen
843+
from = offsets[index]
844+
this.applyMarker(marker)
845+
})
846+
enteredFullScreen = this.applyText(text.slice(from)) || enteredFullScreen
847+
// Judged once the whole read is applied: a program that opened and closed the alternate
848+
// screen and finished within it already has its result, and one that left it is not holding it.
849+
if (enteredFullScreen && this.pendingCommand?.capturing && this.altScreen) {
850+
this.resolveInteractiveCommand()
851+
}
852+
853+
if (text) {
847854
this.pendingOutput += text
848855
this.scheduleFlush()
849856
}
850857
}
851858

859+
/**
860+
* Follows the screen switches in `text` and adds it to the running command's output; true when
861+
* that command entered the alternate screen.
862+
*/
863+
private applyText(text: string): boolean {
864+
if (!text) return false
865+
this.trackAltScreen(text)
866+
if (!this.pendingCommand?.capturing) return false
867+
this.pendingCommand.lastActivityAt = Date.now()
868+
this.captureOutput(this.pendingCommand, text)
869+
return text.includes(ALT_SCREEN_ENTER)
870+
}
871+
852872
private applyMarker(
853873
marker: ReturnType<ShellIntegrationParser['parse']>['markers'][number]
854874
): void {

‎apps/desktop/src/main/terminal/shell-integration.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,12 @@ export interface ParseResult {
5353
/** Stream with the OSC 633 sequences removed, safe to hand to xterm.js. */
5454
text: string
5555
markers: ShellMarker[]
56+
/**
57+
* Where each marker fell in `text`: `markers[i]` came after `text.slice(0, offsets[i])`. A fast
58+
* command's start, output and end can share one chunk, so output belongs to a command only
59+
* between its own markers.
60+
*/
61+
offsets: number[]
5662
}
5763

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

8692
const markers: ShellMarker[] = []
93+
const offsets: number[] = []
8794
let text = ''
8895
let index = 0
8996

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

111118
const body = buffer.slice(start + '\u001b]633;'.length, terminator.index)
112119
const marker = this.toMarker(body)
113-
if (marker) markers.push(marker)
120+
if (marker) {
121+
markers.push(marker)
122+
offsets.push(text.length)
123+
}
114124
index = terminator.index + terminator.length
115125
}
116126

117-
return { text, markers }
127+
return { text, markers, offsets }
118128
}
119129

120130
private toMarker(body: string): ShellMarker | null {

‎apps/sim/app/api/billing/switch-plan/route.test.ts‎

Lines changed: 110 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,26 @@ import { authMockFns, createMockRequest, resetEnvFlagsMock, setEnvFlags } from '
22
import { billingAccessMock, billingAccessMockFns } from '@sim/testing/mocks/billing-access.mock'
33
import { billingCoreMock, billingCoreMockFns } from '@sim/testing/mocks/billing-core.mock'
44
import { billingOrganizationMock } from '@sim/testing/mocks/billing-organization.mock'
5-
import { billingPlanMock } from '@sim/testing/mocks/billing-plan.mock'
5+
import { billingPlanMock, billingPlanMockFns } from '@sim/testing/mocks/billing-plan.mock'
66
import { billingSubscriptionMock } from '@sim/testing/mocks/billing-subscription.mock'
77
import { posthogServerMock } from '@sim/testing/mocks/posthog-server.mock'
8+
import { stripeClientMock } from '@sim/testing/mocks/stripe.mock'
89
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
910

10-
const { mockCanManageWorkspaceBilling, mockGetWorkspaceHostContextForViewer } = vi.hoisted(() => ({
11+
const {
12+
mockCanManageWorkspaceBilling,
13+
mockGetWorkspaceHostContextForViewer,
14+
mockClaimCheckoutAdmission,
15+
mockReleaseCheckoutAdmission,
16+
mockReadSwitchBasis,
17+
mockRecordPlanSwitch,
18+
} = vi.hoisted(() => ({
1119
mockCanManageWorkspaceBilling: vi.fn(),
1220
mockGetWorkspaceHostContextForViewer: vi.fn(),
21+
mockClaimCheckoutAdmission: vi.fn(),
22+
mockReleaseCheckoutAdmission: vi.fn(),
23+
mockReadSwitchBasis: vi.fn(),
24+
mockRecordPlanSwitch: vi.fn(),
1325
}))
1426

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

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

37+
vi.mock('@/lib/billing/stripe-client', () => stripeClientMock)
38+
39+
vi.mock('@/lib/billing/checkout-admission', () => ({
40+
claimCheckoutAdmission: mockClaimCheckoutAdmission,
41+
releaseCheckoutAdmission: mockReleaseCheckoutAdmission,
42+
}))
43+
44+
vi.mock('@/lib/billing/plans', () => ({
45+
getPlanByName: (name: string) => ({
46+
name,
47+
priceId: 'price-month',
48+
annualDiscountPriceId: 'price-year',
49+
}),
50+
}))
51+
52+
vi.mock('@/lib/billing/core/plan-switch', () => ({
53+
readSwitchBasis: mockReadSwitchBasis,
54+
recordPlanSwitch: mockRecordPlanSwitch,
55+
}))
56+
2557
vi.mock('@/lib/billing/workspace-permissions', () => ({
2658
canManageWorkspaceBilling: mockCanManageWorkspaceBilling,
2759
}))
@@ -34,7 +66,9 @@ vi.mock('@/lib/workspaces/host-context', () => ({
3466

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

37-
const { mockGetOrganizationSubscription } = billingCoreMockFns
69+
const { mockGetOrganizationSubscription, mockIsSubscriptionOrgScoped } = billingCoreMockFns
70+
71+
const routeContext = { params: Promise.resolve({}) }
3872

3973
const { mockGetEffectiveBillingStatus } = billingAccessMockFns
4074

@@ -96,7 +130,8 @@ describe('POST /api/billing/switch-plan', () => {
96130
createMockRequest('POST', {
97131
targetPlanName: 'enterprise',
98132
workspaceId: 'workspace-1',
99-
})
133+
}),
134+
routeContext
100135
)
101136

102137
expect(response.status).toBe(400)
@@ -105,4 +140,75 @@ describe('POST /api/billing/switch-plan', () => {
105140
})
106141
expect(mockGetEffectiveBillingStatus).not.toHaveBeenCalled()
107142
})
143+
144+
describe('during a Pro free trial', () => {
145+
const personalPro = (status: string) => ({
146+
id: 'subscription-1',
147+
referenceId: 'viewer-1',
148+
plan: 'pro_6000',
149+
status,
150+
stripeSubscriptionId: 'stripe-subscription-1',
151+
})
152+
const mockStripeUpdate = vi.fn()
153+
154+
beforeEach(() => {
155+
mockGetEffectiveBillingStatus.mockResolvedValue({
156+
billingBlocked: false,
157+
billingBlockedReason: null,
158+
blockedByOrgOwner: false,
159+
})
160+
mockIsSubscriptionOrgScoped.mockResolvedValue(false)
161+
mockClaimCheckoutAdmission.mockResolvedValue({ claimToken: 'claim-1' })
162+
stripeClientMock.requireStripeClient.mockReturnValue({
163+
subscriptions: {
164+
retrieve: vi.fn().mockResolvedValue({
165+
status: 'trialing',
166+
items: {
167+
data: [{ id: 'item-1', price: { id: 'price-1', recurring: { interval: 'month' } } }],
168+
},
169+
}),
170+
update: mockStripeUpdate,
171+
},
172+
})
173+
})
174+
175+
it.each([
176+
{ label: 'a tier change', targetPlanName: 'pro_25000', interval: undefined },
177+
{ label: 'an interval change', targetPlanName: 'pro_6000', interval: 'year' },
178+
])('refuses $label before touching Stripe', async (switchCase) => {
179+
billingPlanMockFns.mockGetHighestPrioritySubscription.mockResolvedValue(
180+
personalPro('trialing')
181+
)
182+
183+
const response = await POST(
184+
createMockRequest('POST', {
185+
targetPlanName: switchCase.targetPlanName,
186+
interval: switchCase.interval,
187+
}),
188+
routeContext
189+
)
190+
191+
expect(response.status).toBe(409)
192+
await expect(response.json()).resolves.toMatchObject({
193+
error: expect.stringContaining('free trial ends'),
194+
})
195+
expect(stripeClientMock.requireStripeClient).not.toHaveBeenCalled()
196+
})
197+
198+
it('refuses a switch Stripe still holds in trial while the row has moved on', async () => {
199+
const subscription = personalPro('active')
200+
billingPlanMockFns.mockGetHighestPrioritySubscription.mockResolvedValue(subscription)
201+
mockReadSwitchBasis.mockResolvedValue({ subscription, pool: undefined })
202+
203+
const response = await POST(
204+
createMockRequest('POST', { targetPlanName: 'pro_6000', interval: 'year' }),
205+
routeContext
206+
)
207+
208+
expect(response.status).toBe(409)
209+
expect(mockStripeUpdate).not.toHaveBeenCalled()
210+
expect(mockRecordPlanSwitch).not.toHaveBeenCalled()
211+
expect(mockReleaseCheckoutAdmission).toHaveBeenCalledWith({ claimToken: 'claim-1' })
212+
})
213+
})
108214
})

‎apps/sim/app/api/billing/switch-plan/route.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { type NextRequest, NextResponse } from 'next/server'
66
import { billingSwitchPlanContract } from '@/lib/api/contracts/subscription'
77
import { parseRequest } from '@/lib/api/server'
88
import { getSession } from '@/lib/auth'
9+
import { TRIAL_PLAN_CHANGE_MESSAGE } from '@/lib/billing/authorization'
910
import {
1011
type CheckoutAdmissionClaim,
1112
claimCheckoutAdmission,
@@ -19,13 +20,14 @@ import {
1920
getHighestPrioritySubscription,
2021
} from '@/lib/billing/core/plan'
2122
import { readSwitchBasis, recordPlanSwitch } from '@/lib/billing/core/plan-switch'
22-
import { getPlanTierCredits, getPlanType, isEnterprise } from '@/lib/billing/plan-helpers'
23+
import { getPlanTierCredits, getPlanType, isEnterprise, isPro } from '@/lib/billing/plan-helpers'
2324
import { getPlanByName } from '@/lib/billing/plans'
2425
import { requireStripeClient } from '@/lib/billing/stripe-client'
2526
import {
2627
hasUsableSubscriptionAccess,
2728
hasUsableSubscriptionStatus,
2829
isOrgScopedSubscription,
30+
isTrialingSubscription,
2931
} from '@/lib/billing/subscriptions/utils'
3032
import { canManageWorkspaceBilling } from '@/lib/billing/workspace-permissions'
3133
import { isBillingEnabled } from '@/lib/core/config/env-flags'
@@ -106,6 +108,13 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
106108
)
107109
}
108110

111+
// A Pro trial's fixed allowance is counted per billing period, and a price change restarts the
112+
// period, so a switch during the trial would start the cap over. Pro is only ever personal.
113+
const isProPlan = isPro(sub.plan)
114+
if (isProPlan && isTrialingSubscription(sub)) {
115+
return NextResponse.json({ error: TRIAL_PLAN_CHANGE_MESSAGE }, { status: 409 })
116+
}
117+
109118
const targetPlan = getPlanByName(targetPlanName)
110119
if (!targetPlan) {
111120
return NextResponse.json({ error: 'Target plan not found' }, { status: 400 })
@@ -156,6 +165,10 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
156165
if (!hasUsableSubscriptionStatus(stripeSubscription.status)) {
157166
return NextResponse.json({ error: 'Stripe subscription is not active' }, { status: 400 })
158167
}
168+
// The row can trail Stripe: a trial whose start webhook has not landed is still a trial.
169+
if (isProPlan && isTrialingSubscription(stripeSubscription)) {
170+
return NextResponse.json({ error: TRIAL_PLAN_CHANGE_MESSAGE }, { status: 409 })
171+
}
159172

160173
const subscriptionItem = stripeSubscription.items.data[0]
161174
if (!subscriptionItem) {

0 commit comments

Comments
 (0)