At 10pm on Thursday 8 June, shadow chancellor John McDonnell, Jeremy Corbyn’s oldest and best political friend, was sitting with Conservative defence secretary Michael Fallon in the glare of the BBC studio lights, preparing for a long night ahead. The general election exit poll was meant to confirm that Theresa May’s gamble had paid off, and she had strengthened her majority. Instead, it suggested Labour was in touching distance of ousting her from Downing Street.

“I was on air when the exit poll was announced,” McDonnell recalled. “I get on all right with Michael, but he’s a tough character, he’s robust. When it came on, I did the usual bit, ‘This is just a poll.’ That’s the standard line for politicians to spout at the early stage of a marathon election night”. But as he glanced at the defence secretary, “the blood drained from his face,” McDonnell said. “When the cameras were off, he was gripping my arm, saying, ‘This can’t be right John, this can’t be right.’ And I was having to calm him down and say, ‘It’s only a poll Michael, don’t worry.’”

The inside story of Labour’s election shock – podcast Read more

Not far away in Islington, Corbyn was watching at home with his wife, Laura Alvarez, and his two closest aides, Karie Murphy and Seumas Milne – who had popped into the corner shop on the way to pick up some bottles of Peroni, knowing that the teetotal Labour leader was unlikely to have stocked up for the occasion.

And what an occasion it was. In that moment – as the exit poll showed Labour stripping Theresa May of her governing majority – this ragtag band of ideologues, who had spent much of their lives fighting on the fringes of British politics, became a government-in-waiting. Corbyn, a 200-1 outsider for the Labour leadership less than two years earlier, sat on his sofa wondering whether he was about to become Britain’s next prime minister. A hung parliament was one of the scenarios his close team of advisers had planned for, but it was at the upper end of their expectations. They hugged each other – but they didn’t believe it yet.

Through a gruelling seven weeks of spats and leaks, Corbyn, widely viewed within his own party as an electoral millstone, went from barely being able to fill his own front bench in parliament to packing out town squares and car parks up and down the country with ardent fans, while his team of leftwing outriders burst into the mainstream of Britain’s political debate.

They didn’t do it alone. None of Corbyn’s high command had run anything on the scale of a nationwide general election campaign. They needed Labour’s party machine, with its spreadsheets and budgets and cumulative wisdom of campaigns gone by. Both sides – Labour apparatchiks and Corbynistas – harboured deep suspicions of each other, and there were bitter battles, over resources and tactics. But ultimately both tribes played their part.

They lost that night, of course: Corbyn’s party took 262 seats to the Tories’ 318, and May remains in Downing Street. But they won, too – against the sceptics inside their own party; against the nip-and-tuck political compromises they felt had marred the last Labour government and the party’s manifestos in 2010 and 2015; against the odds.

And on domestic policy at least, they won the battle of ideas. Ever since election night, May has been relentlessly challenged on public sector pay, on student fees, on the out-of-control housing market – issues forced up the agenda by Labour. And as the parties gather for their autumn conferences – Labour in Brighton, the Conservatives in Manchester – it is May, not Corbyn, who is scrambling to reassert authority over her party. Labour took a lead in the polls immediately after the general election, although more recent surveys have found the parties roughly equal, with May still the more popular choice as prime minister. But the dynamic has changed dramatically, because the Tories no longer feel secure.

“Every lesson all these politics professors ever learned has been proved wrong,” says Jon Trickett, another trusted Corbyn ally, whose analysis helped to shape the campaign’s broad outlines. “I think the dislocation between ordinary people’s lives and the people who run the country has never been greater: they don’t understand what’s going on in the country. That applies to the people that write the newspapers, the people on the telly and some people in our own party. The political centre of gravity in the country was never where they thought it was.”

In spring 2017, Jeremy Corbyn was the leader of a bitterly divided party. He had seen off “the coup”, as his allies still call it – the mass shadow cabinet resignations following the EU referendum that led to a doomed leadership challenge from Owen Smith. But many Labour MPs remained deeply sceptical about his policies and his electability. Privately, some even hoped for a snap election, and the wipeout they were convinced would follow, because it would force Corbyn to resign and mark the end of his leftwing project. A YouGov poll of Labour members in March showed 36% wanted him to resign immediately, while another 14% thought he should go before the next election.

After two vehement critics of the leadership, Tristram Hunt and Jamie Reed, resigned to take jobs outside parliament, Labour faced two byelections in February. The party held Hunt’s seat in Stoke against Ukip’s lacklustre leader Paul Nuttall, but lost Copeland, in Cumbria, to the Tories. It was the first time since 1982 that the governing party had gained a seat in a byelection, and even some of Corbyn’s supporters began to have doubts about Labour’s dire prospects in a general election. “The blame for these results does not lie solely with Jeremy Corbyn,” said Dave Prentis, the head of the public sector union Unison. “But he must take responsibility for what happens next.”

Inside the leadership bunker, the suspicion engendered by the “coup” extended well beyond the restive parliamentary party to the staff and executives at Labour’s own headquarters, and to the media. Corbyn hit out at an ITV reporter in an interview in April, claiming the media were “utterly obsessed” with his leadership, instead of Labour’s policies. Staff at the leader’s office regularly referred to Southside – the party’s main HQ, where party workers were based – as “the dark side”; while McDonnell told the Guardian in March that Corbyn’s team were locked in a “360-degree struggle to survive”.

Among Corbyn’s allies, however, there was always a confidence that he would win through once the public began to focus on Labour’s policies. They believed the drip-drip of seven years of spending cuts had created fertile territory for a conversation about how the economy could be run differently. “The reason a lot of these policies are so popular is that they are things people have wanted for the last 30 years,” said one Labour strategist.

Facebook Twitter Pinterest Jeremy Corbyn with adviser Seumas Milne, May 2017. Photograph: Sean Smith/The Guardian

They had taken advantage of the start of the Easter recess, when parliament is not sitting, to launch a blitz of populist policies, including universal free school meals, funded by imposing VAT on school fees. “It was recess, and our plan for that was: the government will recede; they don’t have a domestic policy agenda, so they won’t be briefing any stories. [We announced] eight policies in 12 days: it was a nice thing. We were 20-plus points behind in the polls; we really needed to shift that,” said one senior member of Corbyn’s media team.

But a few grabby policies is a long way from a fully worked-out manifesto; and a party riven by factional infighting is hardly in the best position to run a nationwide campaign.

On the morning of 18 April, Andrew Gwynne, the chipper Greater Manchester MP who had been appointed Labour’s elections coordinator shortly before the byelections, just happened to be casting an eye over a draft of a “snap election guide” for Labour MPs. Patrick Heneghan, Labour’s longtime in-house elections chief, who had run campaigns for Ed Miliband and Gordon Brown, was showing Gwynne the copy when a message flashed up on his phone from a WhatsApp group of Labour staffers and MPs. It was from Jon Ashworth, the shadow health secretary: “Is there going to be an election, Patrick?”

Gathered in front of the TV at Southside – an anonymous office building near Westminster – the party’s campaign staff heard the prime minister set the date for 8 June, just over seven weeks away. Gwynne, who doesn’t share the penchant of many in the Westminster bubble for foul language, says his reaction was “Crumbs!” But his unfailing optimism made him an ideal candidate to greet the cameras that had quickly massed across from the House of Commons, where, Gwynne recalled, “I was just basically laughed off College Green.”

Back at Southside, a similar view prevailed. Labour were hopelessly unprepared for an election – they had not selected candidates in scores of target seats. The next day, as Labour’s general election team assembled for the first time, it became clear that the deep rift that had developed in the party over the previous 18 months would be played out day by day throughout the campaign. It was a clash of culture and of management style, but it masked more profound divisions about how to patch together an electoral coalition on the left of British politics.

Many of the members of that core team had already been meeting daily to plan Labour’s local election campaign. From Labour HQ, there was party general secretary Iain McNicol, a hate figure on the left of the party after his battle with Corbyn over the rules of the party leadership election in 2016 ended up in the courts; Heneghan, the hardbitten veteran of four general election campaigns; and another seasoned executive, the party’s membership and governance director, Emilie Oldknow. From team Corbyn, there was Gwynne and his co-coordinator Ian Lavery, a passionate former miner and close ally of the leader (who moderate MPs assumed was put in place to ensure Gwynne – highly competent but not a natural Corbynite – didn’t step out of line); Seumas Milne, whose nickname from his time working at the Guardian – “the thin controller” – travelled with him into his job as Corbyn’s most trusted adviser; and Karie Murphy, the Labour leader’s de facto chief of staff and a close ally of Unite head Len McCluskey, whose union is Labour’s biggest donor.

Murphy is little-known publicly, but she controls access to her boss and acts as his enforcer. “The first rule of Corbynism is: you don’t say no to Karie,” says one Labour aide. Shadow ministers quail when her name pops up on their phone, because they know her demands carry her boss’s imprimatur. One political adviser who has worked closely with them said: “They’ve sort of established a dominance. Seumas focuses on message, and she focuses on organisation.” More than one person compared Milne and Murphy to Theresa May’s former joint chiefs of staff, Nick Timothy and Fiona Hill.

Just as the general election team’s first meeting was about to start, party staff were astonished to be asked to wait because Jon Trickett was going to join them. The Yorkshire MP, who had worked closely with Brown and Miliband, had been stripped of responsibility for election planning just two months earlier, after falling out with Murphy – yet with the starting gun fired on a real campaign, Corbyn’s team insisted that he had to be in the room.

Trickett, whose presentations to shadow cabinet meetings had been derided as rambling by some MPs, reprised a paper he had presented to the inner core of the shadow cabinet – Corbyn, McDonnell and Diane Abbott – months earlier, which suggested that by adopting a radical manifesto that was “transformational, not transactional”, Labour could win as much as 41% of the vote, by appealing to social and economic groups deserted by the Tory government. The party should aim to change society, not just offer “so many carrots to so many donkeys”, Trickett said, quoting the prewar socialist thinker RH Tawney.

Hitting 41% would be an extraordinary result – not far behind the 43% Tony Blair achieved in the landslide Labour victory of 1997 – especially for a party then more than 20 points behind in the polls. Trickett’s presentation raised eyebrows among Labour staff, who did not share Team Corbyn’s long-held belief that the public would warm to their unpopular leader when election rules kicked in and broadcasters had to give Labour equal time. “I thought that if we could get broadcast coverage, people would realise what we were about, and realise what Jeremy was like as an individual, and it would turn. Nobody believed me at the time, but it wasn’t wishful thinking,” McDonnell said.

Jeremy Corbyn - a travelling portrait Read more

The sceptical Southsiders had hard-learned electoral lore on their side. History shows that parties rarely narrow the gap in the polls by more than 2 or 3% over the course of a campaign, because “campaigns don’t matter”; that manifestos are all but irrelevant, because voters never read them; and “non-voters are called non-voters for a reason: they don’t vote”.

This divide – between the optimistic Corbynites and more cautious party staff – would flare up repeatedly throughout the campaign, over where and how to allocate campaign funding. One senior member of Corbyn’s team said: “I don’t want to be briefing against Southside, but they were absolutely hopeless, really. Terrible.” When Corbyn’s loyal team – “Loto”, as they are known in party parlance, for leader of the opposition’s office – moved into Southside, junior party staff quickly dubbed them the “Loto-bots”. “Between the Loto-bots and the Southsiders in general, it was complete dysfunction,” said one Labour aide. Labour staffers recalled that “dozens” of Momentum volunteers turned up to play unspecified roles under the direction of Milne, whose reputation for mystery remained. “He’s there one second, and then he’s gone, and no one knows where he is. He shapeshifts.”

At one of the team’s regular planning meetings in early May, there was a row over a list of candidates produced by Southside as potential recipients of financial support. The list was rejected by Team Corbyn because they believed it was designed to shore up centrist MPs, or even to aid potential leadership challengers. “Angela Eagle, Dan Jarvis, Tom Watson, Yvette Cooper: what have they got in common?” said one. (The two sides later agreed that some candidates would be removed from the list.)

Team Corbyn were keen to pursue an offensive strategy, targeting a swath of Tory constituencies, including some in Scotland – though sceptics suggest a truer picture of their beliefs is revealed by the ferocity with which they fought to have favoured candidates adopted in safe seats. But many of those seats did not yet have any candidate selected; and party staff fretted about abandoning longstanding MPs who vehemently believed they were at risk of losing (and had the pollsters on their side). In the end, both sides reached a compromise about how to distribute cash – but from the start, the stage was set for a tug-of-war that would recur throughout the next seven weeks.

With the candidates out on the stump – and on TV and radio broadcasts – the contrasting styles of the challenger and the “strong and stable” prime minister soon became a defining element of the campaign, and Corbyn’s media strategists were eager to turn it to their own advantage.

“That was felt from the beginning,” one Corbyn media adviser told me. “They were polar opposites: she flies in on a helicopter to a golf club; Jeremy gets the train to Croydon and campaigns on the high street. It’s how he likes to do it anyway, but you can cause upsets by doing that – like John Major in 1992 – because of what it communicates about what your politics are like, what your personality is like.”

For door-knocking and getting out their core vote, Corbyn’s campaign was able to draw on a significantly expanded party membership, as well as the activist base supplied by the young, highly motivated members of Momentum. But they also believed, in the face of some scepticism from HQ, that they could reach new groups of voters – by boosting turnout among young people, for example – and engage them in different ways.

So after Corbyn launched his bright red battle bus on 9 May, at a slick, stage-managed event in Manchester that could have been straight out of the Blair era, it trundled off to a nearby shopping centre in Salford, where scores of local supporters alerted by text message, Facebook and WhatsApp gathered to see it arrive. “I’ve brought her to see the next prime minister,” one young mother said, holding up a baby. Many more people saw the crowd and stopped to see what was going on.

Corbyn swept off the bus, shaking hands and exchanging a word or two, clambered on a platform and gave a scrappy stump speech reprising Labour’s education policies and praising local MP Rebecca Long-Bailey; and climbed back aboard the bus to cheers. Not everyone was enthralled – one heckler at the back of the crowd accused Labour of abandoning its working-class backers – but it was noisy, boisterous and memorable.

Facebook Twitter Pinterest Jeremy Corbyn campaigning in Lincoln, June 2017. Photograph: Sean Smith/The Guardian

These mass rallies, which became larger and more raucous as the weeks went on, were regarded as a poor measure of genuine political support by many MPs; but McDonnell says, “the reason we had Jeremy doing the meetings was that we thought word of mouth was important. If we could get enough people to those meetings, then that would translate, particularly into marginal constituencies, into enough votes.”

Corbyn’s schedule was generally arranged to avoid the constituencies of critical Labour MPs defending marginal seats, whose traditional voters were telling them they were no fans of the leader. But big, lively public meetings provided ideal pictures for broadcast coverage, and another contrast with May’s carefully managed events. “If we just put out a policy a day,” the media adviser said, “as long as there’s an overarching narrative – for the many, not the few – each one plays into a zoomed-out message, which is: ‘Labour has a lot to offer that’s nice for you; the Tories have these soundbites.’ And that story gets repeated every day.”

Many of the supporters who joined the rallies – which got increasingly packed as the campaign went on – were summoned on social media; but they were just the tip of a vast digital iceberg. Labour’s digital strategy was overseen by Milne’s deputy, Steve Howell, who has years of experience managing his own PR firm, and made the case throughout the campaign for more resources to be devoted to digital outreach.

Jack Bond, who has long run Corbyn’s Twitter feed, was responsible for overseeing organic content: material that is shared by users – on Facebook, for example – and can quickly gain extraordinary reach. In total, Labour estimates that more than 15 million people watched at least one Jeremy Corbyn video during the campaign. James Schneider, the media-savvy former chair of Momentum, and Sophie Nazemi, another young Momentum staffer, also helped to hone the messages that went out on Facebook and Twitter.

While some of the ads had strong anti-Tory messages, Corbyn urged the team to avoid mudslinging. “There were a number of times he personally called up the digital teams and said: ‘I don’t want lots of negative stuff going out, we should be criticising their record, we should be criticising their policies – I don’t want you to hold back on that, but I don’t want any personal stuff’,” one insider explained.

Tom Lavelle, who already worked on digital strategy in Labour HQ, was in charge of non-organic content: paid-for online advertising. As the campaign budget increased – with a significant boost of £4m from Unite, and a flood of individual donations that ultimately totalled more than £4m – more resources were pushed online, with Lavelle and Howell working together to bid for more cash.

The targeting of ads became more aggressive as the campaign went on, shifting into constituencies Labour hoped to take from the Tories and the Lib Dems. Facebook in particular allowed the party to target paid-for content very precisely: using a custom-built tool called Promote, the campaign was able to match voter information to social media profiles and reach individual voters with precisely tailored ads about the party’s policies. By polling day, they had spent £1.3m on the digital strategy.

As the campaign entered its final stage, the team spent £100,000 in a single day on Twitter ads; and £100,000 in three days on Snapchat, where users could overlay a cheery cartoon Corbyn on their photos to show friends they were voting Labour. To support their strategy of boosting turnout, particularly among young voters, the tech team also built an app called Polling Station Finder. It was seen by 1.24 million people, 910,000 of whom clicked through to find their polling station. A similar project developed by Momentum, called My Nearest Marginal, which directed activists toward the closest competitive seat where they could knock on doors, was used by 100,000 people – although its first iteration sparked a renewed round of infighting when accusations emerged that it excluded marginal seats held by vocal critics of Corbyn.

Corbyn’s outriders wanted to do more than prove they had the right campaign tactics – they were determined to win the battle of ideas, and prove that Labour could offer full-throated socialism without driving voters away.

Before the campaign began, Brexit was the dominant issue, and the shadow cabinet had split over whether to back the government’s legislation allowing them to trigger article 50 and begin the process of leaving the EU. With the Liberal Democrats styling themselves as the party of remain, centrist pro-EU Labour MPs were anxious about being squeezed out – but Corbyn’s team believed the party had to back the results of the referendum to avoid being accused of betraying leave voters in their heartland constituencies, and hoped this would allow them to move the conversation to domestic policy.

Andrew Fisher, Labour’s executive director of policy, spent the fortnight after the election was called in a race against time to complete the manifesto, which would form the intellectual backbone of Labour’s campaign. Notwithstanding their inherent suspicion of focus-group politics as practised by the reviled Tony Blair, their pollsters had been road-testing policies with groups of voters for months. Some had already been floated over Easter, when Labour thought it was only fighting local elections. Promising free school lunches and paying for it by taxing private school fees, for example, pleased parents, while neatly encapsulating Labour’s anti-establishment, “for the many” message. Others, such as rail nationalisation, had been pet projects of Corbyn and McDonnell’s for decades.

Fisher – a former union official and author of a book about privatisation, The Failed Experiment: And How to Build an Economy that Works – drove the process, working closely with the party’s director of policy, Simon Jackson. “Andrew Fisher held the pen on it,” says the media adviser, who called Fisher “the unsung hero of the campaign”.

Corbyn’s team knew that some of their more radical policies would be portrayed as extreme by the rightwing media; but they hoped it would just draw more attention to the ideas. Ashworth, the shadow health secretary, who cut his teeth working for Brown, said the widening impact of seven years of spending cuts had created a receptive audience for Labour’s anti-austerity message. “The first five years of the Conservatives, people knew there were cuts going on, but they didn’t seem to affect their lives. Now, you’re getting a letter through your door saying we can’t afford textbooks, or there’s going to be less teachers next year. And more and more people are finding they’ve got an elderly relative who’s trapped in hospital with nowhere to go; I think the public services cuts played in this election in a way they didn’t in 2015. That’s quite a transformation in two years.”

The drafts of the manifesto were closely guarded prior to its launch: after 18 months of coups and plots, the Loto-bots were so suspicious of their party colleagues that even shadow ministers were only shown sections relevant to their brief. Other key stakeholders, including trade union representatives, were allowed to leaf through a copy – but not take it away.

It turned out those precautions were not tight enough. On 10 May, just under a week before the manifesto was due to be launched, the election team were meeting in Southside when Milne received a phone call from James Schneider in Corbyn’s campaign team: there had been a leak. And not just of a few pages, or a couple of tasty political nuggets. The entire 43-page document had been handed to journalists at the Telegraph and the Mirror.

Facebook Twitter Pinterest Jeremy Corbyn on the way to a rally in Peterborough, May 2017. Photograph: Sean Smith/The Guardian

As the stories appeared online that night, with the Telegraph caricaturing the manifesto as a plan to “take Britain back to the 1970s by nationalising industries, forcing wage caps on businesses and giving huge power to the unions”, a late-night conference call was convened – with an angry Milne in the chair – to formulate a response and identify the mole.

It went on until the early hours, Gwynne recalled. But by then, there was only one plausible option – to ride the sudden wave of interest in Labour’s policies, which were, after all, what Corbyn’s allies regarded as the central part of their pitch to the public. “We reached a collective view that, actually, we’d take it as an opportunity,” Gwynne said. Received wisdom says no one ever reads manifestos; but in the week after it was formally launched in Bradford on 16 May, Labour analysis found that the most-shared political thing on social media was the link to it.

Among stunned Labour insiders, reactions to the leak were divided along ideological lines. Privately, the Loto-bots were quick to point the finger at Tom Watson, the party’s deputy leader and a pantomime baddie for Labour leftwingers. On the other side, rumours began circulating among centrist MPs that the leak was a hoax and the drafts had been deliberately planted by a member of Corbyn’s team – perhaps McDonnell, who enjoys a reputation for skulduggery among the right of the party that rivals Watson’s on the left. “I think someone in that tight-knit leadership group did it,” one centrist party aide said. “And they did it so that we spent a week talking about a load of populist policies.”

The party conducted a forensic investigation of the leak, which finally delivered its report to Labour’s ruling national executive committee earlier this week – and identified the individual responsible for leaking the draft. Their name was not shared with the committee, however – but they are understood to be among those who were consulted on the Scottish draft of the policy document. No further action will be taken, but Corbyn’s team says that the circulation list will be even tighter next time around.

Labour strategists felt they had recovered as well as they could from being knocked off balance by the leak – but they couldn’t have dreamed of the boost they were about to receive, two days later, from the Tory party. Theresa May launched the Conservative manifesto at a former mill near Halifax. It never become clear why she was there, in particular; and the assembled reporters flicked through the little blue book (“Forward Together”) with growing bafflement. There were no costings, and no catchy giveaways to distract voters’ attention from the controversial social care policy that had emerged the night before: the dementia tax, as it was quickly dubbed.

Just four days later, after caving in to intense political pressure and announcing that the government would put a ceiling on overall care costs, May insisted at a testy press conference in Wrexham that “nothing has changed”. For Labour, it was a gift. They had no answer to the challenge of funding long-term social care either – just a promise to consult – but they had plenty of other ideologically sharp policies; and a leader whose unscripted authenticity suddenly appeared to be an asset, in contrast to the Maybot. “It felt like we were in complete chaos and having rows about everything,” the centrist party aide recalled. “But at least we had the rows. It turned out the other side were even worse, and because they were the government, expectations were so much higher.”

Late on the evening of 22 May – the day of May’s U-turn press conference – heartbreaking news began to emerge from Manchester of a terrorist attack on concertgoers, many of them girls and young women. As the full picture began to emerge, Corbyn spoke personally to May, and they agreed to suspend campaigning.

“Your immediate thoughts were: oh God, this is horrible,” says Gwynne. “I knew families that had been at Manchester Arena. The community was really hurting. But part of you thinks: crumbs, the Tory campaign is all about ‘strong and stable’, that Jeremy’s weak on terrorism, security, Theresa May’s the leader – surely this is going to play to her strengths.”

Corbyn’s team were anxious to not surrender the initiative to the prime minister. Insiders at Manchester town hall recall a series of calls from the Labour campaign the next day, trying to ensure Corbyn’s attendance at the vigil in Albert Square that evening. “It felt a bit crass,” said one. As the week wore on, Labour became increasingly keen to get back on the campaign bandwagon. When Corbyn and May spoke again, he told her – unusually forcefully, according to aides who listened in to the call – that Labour intended to resume local campaigning on the Friday, and get back into full election mode on the Saturday.

At Corbyn’s request, and in complete secrecy, Milne worked with his old friend Andrew Murray – McCluskey’s chief of staff, who had been seconded from Unite to help run the campaign – to draft a speech on terrorism and foreign policy. Corbyn, the longtime chair of the Stop the War Coalition, was not about to shy away from his own well-known views on the subject. The speech was cautiously worded, but explicitly made the link between “wars our government has supported or fought in other countries” and “terrorism here at home”, while also attacking cuts to police and emergency services.

Labour press officers had no advance warning of what the speech would say. Headlines in the rightwing press trashed the speech as an outrage, while leading Conservatives proclaimed that Corbyn “should be ashamed”, in the words of Boris Johnson. Some Labour figures in Manchester were also unhappy, and argued it was too soon to be talking about the attack in a political context, however cautiously.

But Corbyn and his closest advisers felt that his foreign policy stance was a selling point, not a weakness. As in so many other areas of the campaign, they did not shy away from Corbyn’s leftwing worldview; they leaned into it. “It was part of a general approach that we had discussed for quite a long time,” the media strategist said. “About how to avoid existing in the other side’s narrative, and instead to have your own – to have things that you talk about confidently rather than trying to triangulate around them.”

It was becoming increasingly clear by this point that momentum was shifting in Labour’s favour, but the wrangles about resources continued. “I think sections of the people advising us were not fast on their feet enough to feel what was happening,” Trickett told me. “I still think that, had we moved faster with our resource allocation, there might have been two or three seats or more that we might have taken.” It is a contention that is rejected firmly by senior Southside sources, who tend to attribute the unexpected result to May’s incompetent campaign as much as the popularity of Corbyn’s leftwing programme – a heated debate that has not died down over the summer. “We lost six seats that we held in 2015,” one senior staffer told me. “If the defensive strategy had been stronger, perhaps we could have held those seats, and the Tories wouldn’t have been able to form a government.”

In the closing days of the campaign, Corbyn loyalists believed there was growing evidence the campaign was moving in their direction. “You got the sense in the constituency and in the country that it was working,” said Trickett. Back at HQ, even party staff who started off outside the Corbyn tent began to be impressed by his growing confidence – and his comfort in his own skin. “He was a good candidate,” one says.

As polling day approached, Corbyn, Milne, Fisher and Murphy met at an anonymous hotel in Victoria to talk through their tactics for a variety of possible results. They decided there were no circumstances in which Corbyn should follow the example of Ed Miliband or Neil Kinnock, and resign in the hours or days after a defeat. But they did agree that in the event of a very bad outcome, it would be necessary to formulate plans to replace Corbyn with a successor from the party’s left.

At 10pm on polling day, McNicol, Heneghan and other senior party staffers, including director of policy Simon Jackson, were up on the eighth floor of Southside, monitoring results as they came in, collating intelligence from counts up and down the country, and trying to stay ahead of the BBC. Around 9.45pm they began hearing rumours about the exit poll from journalists: that it would be “very interesting”, and good for Labour. When the results of the poll were announced, there were a few cries of “utter joy” from where Loto were sitting, one party staffer recalled.

“I think a lot of people resented their jubilation,” the staffer said. “The exit poll they were cheering showed that we had still not won a general election since 2005. We were facing five more years of the Tories. A lot of people will have been fighting this for 12 years by the time of the next election.”

“We were fielding calls from journalists, getting info from sources at the counts. There was a point where the excitement seemed to get too much for people on the ground, and we were told we had won both Shipley and Dover. That turned out to be duff information,” said the party staffer, who was there. “I started to think we might be in government in the morning”. At 1.10am, Heneghan rang Corbyn, and told him Labour’s data showed the Tories had no prospect of forming a majority.

Facebook Twitter Pinterest Jeremy Corbyn and Karie Murphy (left) arrive at Labour HQ the morning after the election. Photograph: Sean Smith/The Guardian

But even that day, Labour MPs with majorities of 10,000 and more, knocking on doors in wards that were meant to be safe, had encountered previous Labour voters saying they were switching to the Conservatives. Many remained convinced until the last moment that they would lose, and their party would plunge to a catastrophic defeat. Potential leadership contenders were quietly planning their next moves.

Labour didn’t win that night, of course, and sceptics were quick to claim that Corbyn had done poorly with the party’s traditional working-class base, particularly in the north. “People have got the impression that it was a terrific result for us,” said Chris Leslie, the Nottingham East MP who has been a fierce critic of Corbyn’s leadership. “In fact it was comparable to Neil Kinnock’s in 1992 – it was a mild improvement, but not nearly enough to get us into Downing Street.”

Professor Stephen Fisher, an elections expert at Oxford, says Labour clearly won the campaign. “The Labour vote rose a lot during the campaign, partly because of people switching away from other parties, but also because a lot of former Labour voters who said they didn’t know in April had returned to the fold by June. This seems to be because Labour party policies were very popular,” Fisher said. In spite of this, he noted, the Conservatives were still seen overall as the best party to manage Brexit and the economy – and May was still regarded by voters as the better choice for prime minister.

But Labour took seats in extraordinary places – Canterbury, Kensington – and made the Tories’ election-winning machine, which had delivered a majority in 2015, look rickety and outdated. More importantly for Corbyn’s band of ideological crusaders, they won the right to set the political agenda. Public sector pay, tuition fees, housing costs, renationalisation: the issues the Conservatives are now being forced to grapple with are those Labour used to make their argument that – as Corbyn told a cheering crowd at Glastonbury at the end of June, “another world is possible”.

Jeremy Corbyn: Labour is now the mainstream, with Tories in disarray Read more

Labour’s civil war has abated as one of the central critiques of Corbyn – that he was unelectable – has fallen away. Owen Smith, who was brutal about the Labour leader when he challenged him last summer, is happily installed in the shadow cabinet. “We’ve had to suck it up,” said one centrist MP.

But there has been no unity reshuffle, and unease within the party over a number of divisive issues has not gone away. On Brexit, which will remain the dominant public policy question for years to come, Labour has a reached a painstaking compromise on the nature of a transition deal, brokered by Keir Starmer. But that fragile truce, on an issue some Labour MPs believe trumps all others, might not hold for long. For now, though, that extraordinary election campaign and its aftermath will continue to make the political weather.

Main illustration by Ellie Foreman-Peck

• Follow the Long Read on Twitter at @gdnlongread, or sign up to the long read weekly email here.